python - 为什么拆包会以元组形式给出结果

标签 python python-2.7 python-3.x

我正在学习任意值参数并阅读 stackoverflow thisthis答案和其他教程我已经了解 *args 和 **kwargs 在 python 中的作用,但我遇到了一些错误。我有两个疑问,第一个是:

如果我运行这段代码 print(w) 那么我得到这个输出:

def hi(*w):
    print(w)

kl = 1, 2, 3, 4
hi(kl)

输出:

((1, 2, 3, 4),)

但是如果我使用 print(*w) 运行这段代码,那么我会得到这样的输出:

代码:

def hi(*w):
    print(*w)

kl = 1, 2, 3, 4
hi(kl)

输出:

(1, 2, 3, 4)

第二个疑惑是:

je = {"a": 2, "b": 4, "c": 6, 4: 5}
for j in je:
    print(*je)

输出

b a 4 c
b a 4 c
b a 4 c
b a 4 c

*je 到底在做什么?它在迭代中是如何工作的?

最佳答案

当您在参数声明中使用 * 时 def hi(*w):,这意味着所有参数将被压缩到元组中,例如:

hi(kl, kl) # ((1, 2, 3, 4), (1, 2, 3, 4))

在您使用 print(*w) * 后运行元组的解包。

je={"a":2,"b":4,"c":6,4:5}
for j in je:
    print(*je)

在每次迭代中,您都使用字典的解包(您使用 je 并获取字典的键,例如 [j for j in je])

https://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments

关于python - 为什么拆包会以元组形式给出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40288553/

相关文章:

Python/tkinter : Change label twice with one command execution

python-3.x - 我们可以一起在docker中设置PHP 7.x和Python 3.x吗?

Python正则表达式在任何地方匹配多个单词

python - 使用 python 从 10 到 N 的步数

python - 二次函数的根 : math domain error

python - 字符串语法不正确,占用超过 1 行 Python

python - 使用 dataframe python 以矩阵格式显示列

python - 如何在循环中为 pytorch 神经网络中的层创建变量名称

python - 如何增加seaborn中图例的字体大小

python - 在 Python 中与 os.system() 并行运行两个可执行文件?