An elegant and fast way to consecutively iterate over two or more containers in Python?

前端 未结 10 1080
太阳男子
太阳男子 2020-12-28 13:29

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)           


        
相关标签:
10条回答
  • 2020-12-28 13:57

    Use itertools.chain(deque1, deque2, deque3)

    0 讨论(0)
  • 2020-12-28 13:58

    How about zip?

    for obj in zip(deque1, deque2, deque3):
        for sub_obj in obj:
            some_action(sub_obj)
    
    0 讨论(0)
  • 2020-12-28 14:02
    >>> a = [[],[],[]]
    >>> b = [[],[],[]]
    >>> for c in [*a,*b]:
        c.append("derp")
    
        
    >>> a
    [['derp'], ['derp'], ['derp']]
    >>> b
    [['derp'], ['derp'], ['derp']]
    >>> 
    
    0 讨论(0)
  • 2020-12-28 14:03

    The answer is in itertools

    itertools.chain(*iterables)
    

    Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Equivalent to:

    def chain(*iterables):
        # chain('ABC', 'DEF') --> A B C D E F
        for it in iterables:
            for element in it:
                yield element
    
    0 讨论(0)
提交回复
热议问题