2017-06-20 51 views
2

我很困惑tee()是如何工作的。itertools tee()迭代器拆分

l = [1, 2, 3, 4, 5, 6] 
iterators3 = itertools.tee(l, 3) 
for i in iterators3: 
    print (list(i)) 

輸出:

[1, 2, 3, 4, 5, 6] 
[1, 2, 3, 4, 5, 6] 
[1, 2, 3, 4, 5, 6] 

這是確定。但是,如果我嘗試:

a, b, c = itertools.tee(l) 

我得到這個錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: not enough values to unpack (expected 3, got 2) 

爲什麼?

+1

你的3在哪裏? –

+0

@MosesKoledoye是的,我現在明白了。 – MishaVacic

+2

@Coldspeed'tee'確實不**返回一個生成器對象,即使它已經生成,你仍然可以解開一個生成器,試試'head,* rest =(我在範圍內(10)),因爲發電機是可迭代的... –

回答

2

tee需要兩個參數,一個迭代器和一個數字,它將複製實際的迭代器(與他的上下文)的次數,你作爲傳遞參數,所以你不能真正解開更多的發電機比開球創造:

a,b = tee(l) #this is ok, since it just duplicate it so you got 2 
a,b,c = tee(l, 3) #this is also ok, you will get 3 so you can unpack 3 
a,b = tee(l, 3) #this will fail, tee is generating 3 but you are trying to unpack just 2 so he dont know how to unpack them 

在Python 3中,你可以解開這樣的:

a, *b = tee(l, 3) 

其中a將從teeb舉行第一次迭代將舉行迭代器的其餘部分s在列表中。