在Python中连续迭代两个或更多容器的优雅而快速的方法? [英] An elegant and fast way to consecutively iterate over two or more containers in Python?

查看:92
本文介绍了在Python中连续迭代两个或更多容器的优雅而快速的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个collection.deques,我需要做的是迭代它们并执行相同的操作:

I have three collection.deques and what I need to do is to iterate over each of them and perform the same action:

for obj in deque1:  
    some_action(obj)  

for obj in deque2:  
    some_action(obj)

for obj in deque3:  
    some_action(obj)

我正在寻找一些功能XXX,理想情况下我可以写:

I'm looking for some function XXX which would ideally allow me to write:

for obj in XXX(deque1, deque2, deque3):  
    some_action(obj)

这里重要的是XXX必须足够高效 - 无需复制或静默使用range()等。我期待在内置函数中找到它,但到目前为止我没有发现任何类似的内容。

The important thing here is that XXX have to be efficient enough - without making copy or silently using range(), etc. I was expecting to find it in built-in functions, but I found nothing similar to it so far.

Python中是否已有这样的东西或我必须写一个我自己的功能是什么?

Is there such thing already in Python or I have to write a function for that by myself?

推荐答案

根据您要处理商品的顺序而定:

Depending on what order you want to process the items:

import itertools

for items in itertools.izip(deque1, deque2, deque3):
    for item in items:
        some_action(item)

for item in itertools.chain(deque1, deque2, deque3):
    some_action(item)

我建议这样做是为了避免硬编码实际的deques或deques数量:

I'd recommend doing this to avoid hard-coding the actual deques or number of deques:

deques = [deque1, deque2, deque3]
for item in itertools.chain(*deques):
    some_action(item)

为了证明上述方法的顺序不同:

To demonstrate the difference in order of the above methods:

>>> a = range(5)
>>> b = range(5)
>>> c = range(5)
>>> d = [a, b, c]
>>>
>>> for items in itertools.izip(*d):
...     for item in items:
...         print item,
...
0 0 0 1 1 1 2 2 2 3 3 3 4 4 4
>>>
>>> for item in itertools.chain(*d):
...     print item,
...
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
>>>

这篇关于在Python中连续迭代两个或更多容器的优雅而快速的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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