Python:Python中的Splat / unpack运算符*不能在表达式中使用吗?
发布于 2021-01-29 18:19:54
有人知道为什么*
不能在涉及迭代器/列表/元组的表达式中使用一元()运算符的原因吗?
为什么只限于功能解压缩?还是我认为这是错误的?
例如:
>>> [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
关注者
0
被浏览
50
1 个回答