Iterating over two lists one after another

前端 未结 3 1354
长情又很酷
长情又很酷 2020-12-06 10:01

I have two lists list1 and list2 of numbers, and I want to iterate over them with the same instructions. Like this:

for item in lis         


        
3条回答
  •  没有蜡笔的小新
    2020-12-06 10:19

    This can be done with itertools.chain:

    import itertools
    
    l1 = [1, 2, 3, 4]
    l2 = [5, 6, 7, 8]
    
    for i in itertools.chain(l1, l2):
        print(i, end=" ")
    

    Which will print:

    1 2 3 4 5 6 7 8 
    

    As per the documentation, chain does the following:

    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.

    If you have your lists in a list, itertools.chain.from_iterable is available:

    l = [l1, l2]
    for i in itertools.chain.from_iterable(l):
        print(i, end=" ")
    

    Which yields the same result.

    If you don't want to import a module for this, writing a function for it is pretty straight-forward:

    def custom_chain(*it):
        for iterab in it:
            yield from iterab
    

    This requires Python 3, for Python 2, just yield them back using a loop:

    def custom_chain(*it):
        for iterab in it:
            for val in iterab:
                yield val
    

    In addition to the previous, Python 3.5 with its extended unpacking generalizations, also allows unpacking in the list literal:

    for i in [*l1, *l2]:
        print(i, end=" ")
    

    though this is slightly faster than l1 + l2 it still constructs a list which is then tossed; only go for it as a final solution.

提交回复
热议问题