gpt4 book ai didi

python - itertools.tee 是如何工作的,可以复制 'itertools.tee' 以保存它的 "status"吗?

转载 作者:太空狗 更新时间:2023-10-29 22:17:06 27 4
gpt4 key购买 nike

下面是一些关于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]

我的问题是

  1. tee 是如何工作的?为什么有时原始 iter“有数据”而有时却没有?
  2. 我可以保留一个 iter 深拷贝作为“状态种子”以保持原始迭代器状态并供以后使用吗?
  3. 我可以交换 2 个迭代器或 2 个 itertools.tee 吗?

谢谢!

最佳答案

tee 接管原来的迭代器;一旦你 tee 一个迭代器,丢弃原来的迭代器,因为 tee 拥有它(除非你真的知道你在做什么)。

您可以使用 copy 模块复制 T 恤:

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)

此时,bc 下的 tee 对象读取了一个值,1。它将它存储在内存中,因为它必须在迭代 c 时记住它。它必须将每个值保存在内存中,直到它被所有 t 恤副本消耗掉。

这样做的结果是您需要小心通过复制 T 恤来“保存状态”。如果您实际上没有使用“已保存状态”T 恤中的任何值,您将导致 T 恤将迭代器返回的每个值永远保存在内存中(直到丢弃复制的 T 恤并收集)。

关于python - itertools.tee 是如何工作的,可以复制 'itertools.tee' 以保存它的 "status"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3957270/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com