python: when can I unpack a generator?

喜夏-厌秋 提交于 2019-12-10 03:24:21

问题


How does it work under the hood? I don't understand the reason for the errors below:

>>> 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

回答1:


The *iterable syntax is only supported in an argument list of a function call (and in function definitions).

In Python 3.x, you can also use it on the left-hand side of an assignment, like this:

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

Edit: Note that there are plans to support the remaining generalisations.




回答2:


Running this in Python 3 gives a more descriptive error message.

>>> *f()
SyntaxError: can use starred expression only as assignment target



回答3:


The two errors are showing the same thing: you can't use * on the left-hand side of an expression.

I'm not sure what you're expecting to happen in those cases, but it's not valid.



来源:https://stackoverflow.com/questions/10967819/python-when-can-i-unpack-a-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!