Python - iterable will split into equal length blocks of data

Explanation

See document found an interesting application (using the zip function)
, for example, [1, 2, 3, 4] -> [(1, 2), (3, 4)], splitting the data block of length 2

Code

>>> a = [1,2,3,4]
>>> length = 2
>>> chunks_len_2 = zip(*[iter(a)] * length)
>>> result = list(chunks_len_2)
>>> result
[(1, 2), (3, 4)]

原理: zip(*iterables)
https://docs.python.org/3/library/functions.html#zip

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

Guess you like

Origin www.cnblogs.com/allen2333/p/11374672.html