/ / itertools tee()イテレータ分割 - python、itertools

itertools tee()イテレータ分割 - python、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は2

tee 2つの引数、イテレータと数値を取る、それは実際のイテレーター(コンテキストで)が引数として渡される回数を複製するので、実際にティーが作成したよりも多くのジェネレーターをアンパックすることはできません:

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 からの最初のイテレータを保持します tee そして b 残りのイテレータはリストに保持されます。