【问题标题】:python: when can I unpack a generator?python:我什么时候可以解压生成器?
【发布时间】:2012-06-10 10:04:08
【问题描述】:

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

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

【问题讨论】:

  • 您在寻找'itertools.consume'吗?
  • 我想他可能正在寻找list(f()) 或tuple(f())。
  • 抱歉,我更想知道 *Generator 是如何工作的,以及你可以在哪里使用它。

标签: python args iterable-unpacking


【解决方案1】:

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

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

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

编辑:注意有plans to support the remaining generalisations。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-09-19
        • 1970-01-01
        • 2011-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-24
        • 1970-01-01
        相关资源
        最近更新 更多