itertools tee()迭代器拆分

时间:2017-06-20 09:17:50

标签: 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 个答案:

答案 0 :(得分:2)

tee有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将保存来自tee的第一个迭代器,而b将其余的迭代器保存在列表中。