将一对发电机变成一对发电机 [英] Turning a generator of pairs into a pair of generators

查看:75
本文介绍了将一对发电机变成一对发电机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何转换成对的生成器(元组):

How would I turn a generator of pairs (tuples):

tuple_gen = (i for i in [(1, "a"), (2, "b"), (3, "c")])

分为两个生成器,分别生成[1, 2, 3]["a", "b", "c"]?

Into two generators which would yield [1, 2, 3] and ["a", "b", "c"]?

我需要分别处理元组的第一和第二个元素,并且处理函数期望可迭代.

I need to process separately the first and second elements of the tuples and the processing functions expect an iterable.

生成器非常大(数百万个项目),因此除非没有其他解决方案,否则我想避免将所有项目同时存储在内存中.

The generator is very large (millions of items) so I'd like to avoid having all items in memory at the same time unless there is no other solution.

推荐答案

您可以使用

You can create n distinct iterators using the tee function from the itertools package. You would then iterate over them separately:

from itertools impor tee

i1, i2 = tee(tuple_gen, n=2)
firsts = (x[0] for x in i1)
seconds = (x[1] for x in i2)

这篇关于将一对发电机变成一对发电机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆