我很困惑 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)
为什么?
最佳答案
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
将保存列表中的其余迭代器。
关于python - itertools tee() 迭代器分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44648839/