29

Does anybody know the reasoning as to why the unary (*) operator cannot be used in an expression involving iterators/lists/tuples?

Why is it only limited to function unpacking? or am I wrong in thinking that?

For example:

>>> [1,2,3, *[4,5,6]]
File "<stdin>", line 1
[1,2,3, *[4,5,6]]
        ^
SyntaxError: invalid syntax

Why doesn't the * operator:

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

whereas when the * operator is used with a function call it does expand:

f(*[4, 5, 6]) is equivalent to f(4, 5, 6)

There is a similarity between the + and the * when using lists but not when extending a list with another type.

For example:

# 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
4

3 回答 3

44

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

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]

以下是对这一变化背后的基本原理的一些解释。请注意,这并不*[1, 2, 3]等同于1, 2, 3在所有情况下。Python 的语法并不打算以这种方式工作。

于 2016-01-13T12:53:07.793 回答
5

Asterix* 不仅仅是一元运算符,它是 函数定义函数调用的参数解包运算符。

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

注意:从 python3.5 开始, *不仅可以与函数 params 一起使用, @B 。M的回答很好地描述了 python 的变化。

如果您需要连接列表,请使用连接list1 + list2来获得所需的结果。要连接列表和生成器,只需传递generatorlist类型对象,然后与另一个列表连接:

gen = (x for x in range(10))
[] + list(gen)
于 2016-01-13T12:32:02.507 回答
3

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

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

于 2016-01-13T12:35:58.730 回答