Python: Splat/unpack operator * in python 不能用在表达式中?
Python: Splat/unpack operator * in python cannot be used in an expression?
有人知道为什么一元 (*
) 运算符不能用于涉及 iterators/lists/tuples 的表达式吗?
为什么只限于函数解包?还是我的想法错了?
例如:
>>> [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
Asterix *
不仅仅是一元运算符,它是 argument-unpacking 运算符 for functions definitions and functions calls.
所以*
应该仅用于函数参数,不用于列表、元组等
注意:从python3.5开始,*
不仅可以与函数参数一起使用,的答案也很好在 python.
中描述了这一变化
如果您需要连接列表,请改用连接 list1 + list2
以获得所需的结果。
要连接列表和 generator 只需将 generator
传递给 list
类型对象,然后再与另一个列表连接:
gen = (x for x in range(10))
[] + list(gen)
这是不支持的。 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 to f(4,5,6)
函数参数展开是一种特殊情况。
已在 Python 3.5
中添加列表、字典、集合和元组文字的解包,如 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 的语法不适合那样工作。
有人知道为什么一元 (*
) 运算符不能用于涉及 iterators/lists/tuples 的表达式吗?
为什么只限于函数解包?还是我的想法错了?
例如:
>>> [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
Asterix *
不仅仅是一元运算符,它是 argument-unpacking 运算符 for functions definitions and functions calls.
所以*
应该仅用于函数参数,不用于列表、元组等
注意:从python3.5开始,*
不仅可以与函数参数一起使用,
如果您需要连接列表,请改用连接 list1 + list2
以获得所需的结果。
要连接列表和 generator 只需将 generator
传递给 list
类型对象,然后再与另一个列表连接:
gen = (x for x in range(10))
[] + list(gen)
这是不支持的。 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)
函数参数展开是一种特殊情况。
已在 Python 3.5
中添加列表、字典、集合和元组文字的解包,如 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 的语法不适合那样工作。