2012-06-10 30 views
7

它如何在引擎蓋下工作?我不明白下面的錯誤的原因:python:我什麼時候可以解開一個發生器?

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

您是否在尋找[ 'itertools.consume'](http://docs.python.org/library/itertools.html#recipes)? – katrielalex

+0

我想他可能正在尋找'list(f())'或'tuple(f())'。 –

+0

對不起,我更想知道* Generator如何工作,以及在哪裏可以使用它。 –

回答

9

*iterable語法僅在函數調用的參數列表(和函數定義中)中受支持。

在Python 3.x中,你也可以用它在賦值的左側,這樣的:

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

編輯:請注意,有plans to support the remaining generalisations

1

兩個錯誤都出現了同樣的事情:你不能在一個表達式的左側使用*

我不確定你在這些情況下會發生什麼,但它是無效的。

4

在Python 3中運行這個提供了一個更具描述性的錯誤信息。

>>> *f() 
SyntaxError: can use starred expression only as assignment target 
相關問題