Skip to main content
 首页 » 编程设计

python之itertools tee() 迭代器拆分

2024年10月01日7java哥

我很困惑 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 将保存列表中的其余迭代器。