Python:python中的Splat / unpack运算符*不能用在表达式中?

问题描述 投票:24回答:3

有没有人知道为什么一元(*)运算符不能用在涉及迭代器/列表/元组的表达式中的原因?

为什么它只限于功能拆包?或者我认为错了?

例如:

>>> [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
python python-2.7 iterable-unpacking argument-unpacking pep448
3个回答
36
投票

3.5中所述,Python PEP 448中添加了列表,字典,集合和元组文字中的解包:

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) on Windows (64 bits).

>>> [1, 2, 3, *[4, 5, 6]]
[1, 2, 3, 4, 5, 6]

Here是对这一变化背后的理由的一些解释。请注意,这并不会使*[1, 2, 3]在所有上下文中等同于1, 2, 3。 Python的语法不是以这种方式工作的。


5
投票

Asterix *不仅仅是一元运算符,它是functions definitionsfunctions calls的参数解包运算符。

所以*应该只用于函数参数而不是列表,元组等。

注意:从python3.5开始,*不仅可以用于函数参数,@B. M的答案大大描述了python的变化。

如果你需要连续列表使用连接而不是list1 + list2来获得所需的结果。要连接列表和生成器,只需将generator传递给list类型对象,之前与另一个列表连接:

gen = (x for x in range(10))
[] + list(gen)

2
投票

这不受支持。 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)

函数参数展开是一种特殊情况。

© www.soinside.com 2019 - 2024. All rights reserved.