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

前端 未结 10 1175
太阳男子
太阳男子 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:47

    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)
    

    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
    >>>
    

提交回复
热议问题