如何合并两个 python 迭代器? [英] How do I merge two python iterators?

查看:23
本文介绍了如何合并两个 python 迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个迭代器,一个 list 和一个 itertools.count 对象(即无限值生成器).我想将这两个合并到一个结果迭代器中,该迭代器将在两者之间交替产生值:

<预><代码>>>>导入迭代工具>>>c = itertools.count(1)>>>项目 = ['foo', 'bar']>>>合并 = imerge(items, c) # 神话中的imerge">>>合并.next()'富'>>>合并.next()1>>>合并.next()'酒吧'>>>合并.next()2>>>合并.next()回溯(最近一次调用最后一次):...停止迭代

最简单、最简洁的方法是什么?

解决方案

一个生成器将很好地解决您的问题.

def imerge(a, b):对于 i, j 在 itertools.izip(a,b) 中:产量我产量 j

I have two iterators, a list and an itertools.count object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:

>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c)  # the mythical "imerge"
>>> merged.next()
'foo'
>>> merged.next()
1
>>> merged.next()
'bar'
>>> merged.next()
2
>>> merged.next()
Traceback (most recent call last):
    ...
StopIteration

What is the simplest, most concise way to do this?

解决方案

A generator will solve your problem nicely.

def imerge(a, b):
    for i, j in itertools.izip(a,b):
        yield i
        yield j

这篇关于如何合并两个 python 迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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