At the same time different iterations of container elements

When there are multiple different sequences (container) need to iterate more common way is to write for loop, or write the following code:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E E
    for it in iterables:
        for element in it:
            yield element

itertools chain module provides a method, a plurality of different types of container may be combined sequentially iteration. as follows:

>>> from itertools import chain
>>> a = [1, 2, 3, 4]
>>> b = ['x', 'y', 'z']
>>> for x in chain(a, b):
        print(x)
...
1
2
3
4
x
y
z 
>>>

Guess you like

Origin www.cnblogs.com/jeffrey-yang/p/11826353.html