An elegant and fast way to consecutively iterate o

2020-02-20 07:12发布

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)

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

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

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.

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

9条回答
倾城 Initia
2楼-- · 2020-02-20 07:58

Call me crazy, but why is using itertools thought to be necessary? What's wrong with:

def perform_func_on_each_object_in_each_of_multiple_containers(func, containers):
    for container in containers:
        for obj in container:
            func(obj)

perform_func_on_each_object_in_each_of_multiple_containers(some_action, (deque1, deque2, deque3)

Even crazier: you probably are going to use this once. Why not just do:

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

What's going on there is immediately obvious without having to look at the code/docs for the long-name function or having to look up the docs for itertools.something()

查看更多
The star\"
3楼-- · 2020-02-20 08:02

If I understand your question correctly, then you can use map with the first argument set to None, and all the other arguments as your lists to iterate over.

E.g (from an iPython prompt, but you get the idea):

In [85]: p = [1,2,3,4]

In [86]: q = ['a','b','c','d']

In [87]: f = ['Hi', 'there', 'world', '.']

In [88]: for i,j,k in map(None, p,q,f):
   ....:     print i,j,k
   ....:
   ....:
1 a Hi
2 b there
3 c world
4 d .
查看更多
何必那么认真
4楼-- · 2020-02-20 08:05

How about zip?

for obj in zip(deque1, deque2, deque3):
    for sub_obj in obj:
        some_action(sub_obj)
查看更多
登录 后发表回答