我正在学习任意值参数并阅读 stackoverflow this和 this答案和其他教程我已经了解 *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/