[英]Python: Splat/unpack operator * in python cannot be used in an expression?
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
Unpacking in list, dict, set, and tuple literals has been added in Python 3.5
, as described in PEP 448 : 如PEP 448中所述,已在Python
3.5
添加了列表,字典,集合和元组文字的解包功能:
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 are some explanations for the rationale behind this change. 以下是此更改背后原因的一些解释。 Note that this does not make
*[1, 2, 3]
equivalent to 1, 2, 3
in all contexts. 请注意,这并不是使
*[1, 2, 3]
在所有情况下都等于1, 2, 3
。 Python's syntax is not intended to work that way. Python的语法不适合这种方式。
Asterix *
isn't simply unary operator, it's argument-unpacking operator for functions definitions and functions calls . Asterix
*
不仅仅是一元运算符,它还是函数定义和函数调用的参数解压缩运算符 。
So *
supposed to be used only to work with function params and not with lists, tuples etc. 所以
*
应该仅用于函数参数, 而不用于列表,元组等。
NOTE: starting from python3.5, *
could be used not only with functions params, @B. 注意:从python3.5开始,
*
不仅可以与函数params @B一起使用。 M 's answer greatly describes that change in python. M的答案很大程度上描述了python中的更改。
If you need to concat lists use concatenation instead list1 + list2
to get desired result. 如果需要合并列表,请使用串联代替
list1 + list2
以获得所需的结果。 To concatenate list and generator simply pass generator
to list
type object, prior concatenating with another list: 要连接列表和生成器,只需将
generator
器传递给list
类型对象,然后再与另一个列表连接:
gen = (x for x in range(10))
[] + list(gen)
This is not supported. 不支持。 Python 3 gives a better message (though Python 2 does not support
*
in the left part of an assignment, afaik): 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])
is equivalent tof(4,5,6)
f(*[4,5,6])
等效于f(4,5,6)
Function argument unfolding is a special case. 函数参数展开是一个特例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.