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

时间:2016-01-13 12:24:52

标签: python python-2.7 iterable-unpacking argument-unpacking pep448

有没有人知道为什么一元(public void slidefromRightToLeft(View view) { TranslateAnimation animate; if (view.getHeight() == 0) { main_layout.getHeight(); // parent layout animate = new TranslateAnimation(main_layout.getWidth()/2, 0, 0, 0); } else { animate = new TranslateAnimation(view.getWidth(),0, 0, 0); // View for animation } animate.setDuration(500); animate.setFillAfter(true); view.startAnimation(animate); view.setVisibility(View.VISIBLE); // Change visibility VISIBLE or GONE } )运算符不能用在涉及迭代器/列表/元组的表达式中?

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

例如:

*

为什么不是>>> [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) +之间存在相似性,但在使用其他类型扩展列表时则不相似。

例如:

*

3 个答案:

答案 0 :(得分:36)

已在Python 3.5中添加了列表,dict,set和tuple文字中的解包,如 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的语法无意以这种方式工作。

答案 1 :(得分:5)

Asterix * 不是一元运算符,它是functions definitions和{{的参数解包运算符 3}}

所以*应该只使用 来处理函数参数和不使用列表,元组等。

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

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

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

答案 2 :(得分: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)

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

相关问题