下面是一些关于itertools.tee的测试
li = [x for x in range(10)]
ite = iter(li)
==================================================
it = itertools.tee(ite, 5)
>>> type(ite)
<type 'listiterator'>
>>> type(it)
<type 'tuple'>
>>> type(it[0])
<type 'itertools.tee'>
>>>
>>> list(ite)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0]) # here I got nothing after 'list(ite)', why?
[]
>>> list(it[1])
[]
====================play again===================
>>> ite = iter(li)
it = itertools.tee(ite, 5)
>>> list(it[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[2])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[3])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[4])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(ite)
[] # why I got nothing? and why below line still have the data?
>>> list(it[0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0])
[]
====================play again===================
>>> ite = iter(li)
itt = itertools.tee(it[0], 5) # tee the iter's tee[0].
>>> list(itt[0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(itt[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0])
[] # why this has no data?
>>> list(it[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(ite)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 我的问题是
tee是如何工作的?为什么有时原始的iter‘有数据’,而其他时候没有?
谢谢!
发布于 2010-10-18 08:04:53
tee接管了最初的迭代器;一旦您为迭代器做了准备,就放弃原来的迭代器,因为tee拥有它(除非您真正知道自己在做什么)。
您可以使用copy模块复制tee:
import copy, itertools
it = [1,2,3,4]
a, b = itertools.tee(it)
c = copy.copy(a)..。或者打电话给a.__copy__()。
请注意,tee的工作方式是跟踪从原始迭代器中使用的所有迭代值,这些值可能仍然由副本使用。
例如,
a = [1,2,3,4]
b, c = itertools.tee(a)
next(b)此时,作为b和c基础的tee对象已经读取了一个值1。它将其存储在内存中,因为当c被迭代时,它必须记住它。它必须将所有的值保存在内存中,直到它被tee的所有副本所消耗为止。
这样做的结果是,您需要通过复制一个tee来小心保存状态。如果您实际上不使用来自“保存状态”tee的任何值,那么将导致tee将迭代器返回的每个值永远保存在内存中(直到复制的tee被丢弃和收集为止)。
https://stackoverflow.com/questions/3957270
复制相似问题