有没有人知道为什么一元(*
)运算符不能用在涉及迭代器/列表/元组的表达式中的原因?
为什么它只限于功能拆包?或者我认为错了?
例如:
>>> [1,2,3, *[4,5,6]]
File "<stdin>", line 1
[1,2,3, *[4,5,6]]
^
SyntaxError: invalid syntax
为什么不是*
运营商:
[1, 2, 3, *[4, 5, 6]] give [1, 2, 3, 4, 5, 6]
而当*
运算符与函数调用一起使用时,它会扩展:
f(*[4, 5, 6]) is equivalent to f(4, 5, 6)
+
和*
在使用列表时有相似之处,但在扩展其他类型的列表时却没有。
例如:
# This works
gen = (x for x in range(10))
def hello(*args):
print args
hello(*gen)
# but this does not work
[] + gen
TypeError: can only concatenate list (not "generator") to list
Asterix *
不仅仅是一元运算符,它是functions definitions和functions calls的参数解包运算符。
所以*
应该只用于函数参数而不是列表,元组等。
注意:从python3.5开始,*
不仅可以用于函数参数,@B. M的答案大大描述了python的变化。
如果你需要连续列表使用连接而不是list1 + list2
来获得所需的结果。要连接列表和生成器,只需将generator
传递给list
类型对象,之前与另一个列表连接:
gen = (x for x in range(10))
[] + list(gen)
这不受支持。 Python 3提供了更好的消息(尽管Python 2在作业的左侧部分不支持*
,afaik):
Python 3.4.3+ (default, Oct 14 2015, 16:03:50)
>>> [1,2,3, *[4,5,6]]
File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target
>>>
f(*[4,5,6])
相当于f(4,5,6)
函数参数展开是一种特殊情况。