在Python中,varargs集合的工作方式似乎与赋值语句中序列解包的工作方式截然不同。我正在试图理解这种潜在的令人困惑的差异的原因。我相信有一个很好的理由,但它是什么呢?
# Example 1 with assignment statement
a, *b, c = 1,2,3,4
print(b) # [2, 3]
# Example 1 with function call
def foo(a, *b, c):
print(b)
foo(1,2,3,4)
函数调用会导致以下错误:
Traceback (most recent call last):
File "<pyshell#309>", line 1, in <module>
foo(1,2,3,4)
TypeError: foo() missing 1 required keyword-only argument: 'c'
问题1:为什么不像赋值语句中那样赋值b?
# Example 2 with function call
def foo(*x):
print(x)
print(type(x))
foo(1,2,3) # (1, 2, 3) <class 'tuple'>
# Example 2 with assignment statement
a, *b, c = 1,2,3,4,5
print(b) # [2, 3, 4]
print(type(b)) # <class 'list'>
问题2:为什么类型(列表和元组)存在差异?
https://stackoverflow.com/questions/56763143
复制相似问题