Python - 将iterable拆分成等长的数据块

说明

看文档发现一个有趣的应用(利用zip函数)
例如[1, 2, 3, 4] --> [(1, 2), (3, 4)],拆分成长度为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)
posted @ 2019-08-19 00:03  Rocin  阅读(234)  评论(0编辑  收藏  举报