首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >itertools.tee是如何工作的,是否可以复制'itertools.tee‘以保存它的“状态”?

itertools.tee是如何工作的,是否可以复制'itertools.tee‘以保存它的“状态”?
EN

Stack Overflow用户
提问于 2010-10-18 07:34:32
回答 1查看 10.9K关注 0票数 9

下面是一些关于itertools.tee的测试

代码语言:javascript
复制
    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‘有数据’,而其他时候没有?

  1. 可以保留一个iter的深拷贝作为“状态种子”来保持原始迭代器状态并在以后使用它吗?
  2. 可以交换2条或2条
  3. 吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-10-18 08:04:53

tee接管了最初的迭代器;一旦您为迭代器做了准备,就放弃原来的迭代器,因为tee拥有它(除非您真正知道自己在做什么)。

您可以使用copy模块复制tee:

代码语言:javascript
复制
import copy, itertools
it = [1,2,3,4]
a, b = itertools.tee(it)
c = copy.copy(a)

..。或者打电话给a.__copy__()

请注意,tee的工作方式是跟踪从原始迭代器中使用的所有迭代值,这些值可能仍然由副本使用。

例如,

代码语言:javascript
复制
a = [1,2,3,4]
b, c = itertools.tee(a)
next(b)

此时,作为bc基础的tee对象已经读取了一个值1。它将其存储在内存中,因为当c被迭代时,它必须记住它。它必须将所有的值保存在内存中,直到它被tee的所有副本所消耗为止。

这样做的结果是,您需要通过复制一个tee来小心保存状态。如果您实际上不使用来自“保存状态”tee的任何值,那么将导致tee将迭代器返回的每个值永远保存在内存中(直到复制的tee被丢弃和收集为止)。

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3957270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档