我有两个迭代器,一个是 list
,另一个是 itertools.count
对象(即一个无限值生成器)。我想将这两个合并成一个结果迭代器,该迭代器会在两者之间交替产生值:
>>> 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
最简单、最简洁的方法是什么?
list((yield next(c)) or i for i in items)
- Chris_Randsheapq.merge
。 - Dennis