在 Python 中的迭代器之间交替

Alternating between iterators in Python(在 Python 中的迭代器之间交替)
本文介绍了在 Python 中的迭代器之间交替的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 Python 中交替从不同迭代器获取值的最有效方法是什么,例如 alternate(xrange(1, 7, 2), xrange(2, 8, 2)) 将产生 1、2、3、4、5、6.我知道实现它的一种方法是:

What is the most efficient way to alternate taking values from different iterators in Python, so that, for example, alternate(xrange(1, 7, 2), xrange(2, 8, 2)) would yield 1, 2, 3, 4, 5, 6. I know one way to implement it would be:

def alternate(*iters):
    while True:
        for i in iters:
            try:
                yield i.next()
            except StopIteration:
                pass

但是有没有更有效或更清洁的方法?(或者,更好的是,我错过了一个 itertools 函数?)

But is there a more efficient or cleaner way? (Or, better yet, an itertools function I missed?)

推荐答案

zip呢?你也可以试试 itertools 的 izip

what about zip? you may also try izip from itertools

>>> zip(xrange(1, 7, 2),xrange(2, 8 , 2))
[(1, 2), (3, 4), (5, 6)]

如果这不是您想要的,请在您的问题帖子中提供更多示例.

if this is not what you want, please give more examples in your question post.

这篇关于在 Python 中的迭代器之间交替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)