gpt4 book ai didi

python - 如何使 itertools.tee() 生成迭代元素的副本?

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:00 26 4
gpt4 key购买 nike

我正在使用 itertools.tee 用于制作生成器的副本,该副本生成字典并将迭代的字典传递给我无法控制且可能会修改字典的函数。因此,我想将字典的副本传递给函数,但所有 tee 只产生对同一实例的引用。

这可以通过以下简单示例进行说明:

import itertools

original_list = [{'a':0,'b':1}, {'a':1,'b':2}]
tee1, tee2 = itertools.tee(original_list, 2)

for d1, d2 in zip(tee1, tee2):
d1['a'] += 1
print(d1)
d2['a'] -= 1
print(d2)

输出为:

{'b': 1, 'a': 1}
{'b': 1, 'a': 0}
{'b': 2, 'a': 2}
{'b': 2, 'a': 1}

虽然我想要:

{'b': 1, 'a': 1}
{'b': 1, 'a': -1}
{'b': 2, 'a': 2}
{'b': 2, 'a': 0}

当然,在这个例子中,有很多方法可以轻松解决这个问题,但由于我的具体用例,我需要 itertools.tee 的版本它将所有迭代对象的副本存储在 tee 队列中,而不是对原始对象的引用。

有没有一种简单的方法可以在 Python 中执行此操作,或者我必须重新实现 itertools.tee以非原生且低效的方式?

最佳答案

无需返工tee。只需将 tee 生成的每个生成器包装在 map(dict, ...) 生成器中即可:

try:
# use iterative map from Python 3 if this is Python 2
from future_builtins import map
except ImportError:
pass

tee1, tee2 = itertools.tee(original_list, 2)
tee1, tee2 = map(dict, tee1), map(dict, tee2)

当您迭代时,这会自动生成每个字典的浅拷贝。

演示(使用 Python 3.6):

>>> import itertools
>>> original_list = [{'a':0,'b':1}, {'a':1,'b':2}]
>>> tee1, tee2 = itertools.tee(original_list, 2)
>>> tee1, tee2 = map(dict, tee1), map(dict, tee2)
>>> for d1, d2 in zip(tee1, tee2):
... d1['a'] += 1
... print(d1)
... d2['a'] -= 1
... print(d2)
...
{'a': 1, 'b': 1}
{'a': -1, 'b': 1}
{'a': 2, 'b': 2}
{'a': 0, 'b': 2}

关于python - 如何使 itertools.tee() 生成迭代元素的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41661241/

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