10

它是如何在引擎盖下工作的?我不明白以下错误的原因:

>>> def f():
...     yield 1,2
...     yield 3,4
...
>>> *f()
  File "<stdin>", line 1
    *f()
    ^
SyntaxError: invalid syntax
>>> zip(*f())
[(1, 3), (2, 4)]
>>> zip(f())
[((1, 2),), ((3, 4),)]
>>> *args = *f()
File "<stdin>", line 1
  *args = *f()
    ^
SyntaxError: invalid syntax
4

3 回答 3

13

*iterable语法仅在函数调用的参数列表(和函数定义)中受支持。

在 Python 3.x 中,您还可以在赋值的左侧使用它,如下所示:

[*args] = [1, 2, 3]

编辑:请注意,有计划支持其余的概括

于 2012-06-10T10:06:42.960 回答
5

在 Python 3 中运行它会给出更具描述性的错误消息。

>>> *f()
SyntaxError: can use starred expression only as assignment target
于 2012-06-10T10:06:53.067 回答
1

这两个错误显示的是同一件事:您不能*在表达式的左侧使用。

我不确定在这些情况下你期望发生什么,但它是无效的。

于 2012-06-10T10:06:31.970 回答