python - itertools tee() 迭代器分割

标签 python 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)

为什么?

最佳答案

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/

相关文章:

python - 如何将悬停突出显示添加到 Bokeh 步骤图

python - 类型错误 : unsupported operand type(s) for/: 'Decimal' and 'float'

python - 找出数字组合中的最高总和

python - 使用 itertools.chain 生成器的返回值

python - Flask_simpleldap 不会绑定(bind)

python - 在 python 中使用 Iterable 和 numeric 作为函数的输入

python - 在 Elasticsearch 中的某些字段上禁用搜索

python - Itertools 生成乱码组合

Python 迭代工具

python - 将列表拆分为所有组合