一起循环两个发电机 [英] Loop over two generator together

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

问题描述

我有两个生成器,分别是A()B().我想一起迭代两个生成器.像这样:

I have two generators say A() and B(). I want to iterate over both the generators together. Something like:

for a,b in A(),B():    # I know this is wrong
    #do processing on a and b

一种方法是将两个函数的结果存储在列表中,然后在合并的列表上循环.像这样:

One way is to store the results of both the functions in lists and then loop over the merged list. Something like this:

resA = [a for a in A()]
resB = [b for b in B()]
for a,b in zip(resA, resB):
    #do stuff

如果您想知道,那么是的,这两个函数都产生相等数量的值.

但是我不能使用这种方法,因为A()/B()返回的值太多.将它们存储在列表中会耗尽内存,这就是为什么我使用生成器.

But I can't use this approach because A()/B() returns so many values. Storing them in a list would exhaust the memory, that's why I am using generators.

有没有办法一次遍历两个生成器?

推荐答案

您几乎在那里.在Python 3中,只需将生成器传递给zip():

You were almost there. In Python 3, just pass the generators to zip():

for a, b in zip(A(), B()):

zip()接受任何迭代,而不仅仅是列表.它将一一消耗掉发电机.

zip() takes any iterable, not just lists. It will consume the generators one by one.

在Python 2中,使用 itertools.izip() :

In Python 2, use itertools.izip():

from itertools import izip

for a, b in izip(A(), B()):

顺便说一句,将生成器转换为列表就像list(generator)一样简单;无需在那里使用列表推导.

As an aside, turning a generator into a list is as simple as list(generator); no need to use a list comprehension there.

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

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