Har*_*Har 25 python argument-unpacking python-2.7 iterable-unpacking pep448
有没有人知道为什么unary(*)运算符不能用在涉及iterators/lists/tuples的表达式中的原因?
为什么它只限于功能拆包?或者我认为错了?
例如:
>>> [1,2,3, *[4,5,6]]
File "<stdin>", line 1
[1,2,3, *[4,5,6]]
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
为什么不是*运营商:
[1, 2, 3, *[4, 5, 6]] give [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
而当*操作符与函数调用一起使用时,它会扩展:
f(*[4, 5, 6]) is equivalent to f(4, 5, 6)
Run Code Online (Sandbox Code Playgroud)
使用列表时+和*使用列表时之间存在相似性,但在使用其他类型扩展列表时则不相似.
例如:
# 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
Run Code Online (Sandbox Code Playgroud)
B. *_* M. 37
不允许在Python 3.5中解压缩已经注意到并在Python *[1, 2, 3]中修复,现在具有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]
Run Code Online (Sandbox Code Playgroud)
以下是对此变更背后的理由的一些解释.
阿斯特里克斯* 不只是一元运算符,它的 参数,拆包经营者对函数的定义和函数的调用.
所以*应该只用于函数参数而不是列表,元组等.
注意:从python3.5开始, *不仅可以用于函数参数,@ B. M的回答大大描述了python的变化.
如果需要连续列表,请使用连接list1 + list2来获得所需的结果.要连接列表和生成器,只需传递generator给list类型对象,事先与另一个列表连接:
gen = (x for x in range(10))
[] + list(gen)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8942 次 |
| 最近记录: |