内置函数 zip( )的使用

翻译中文文档

zip([iterable, ...])

该函数返回一个元组的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。返回的列表长度被截断为最短的参数序列的长度。当多个参数都具有相同的长度时,zip()类似于带有一个初始参数为None的map()。只有一个序列参数时,它返回一个1元组的列表。没有参数时,它返回一个空的列表。

可以保证迭代按从左向右的计算顺序。这使得使用zip(\*[iter(s)]*n)来将一系列数据分类归并为长度为n的组成为习惯用法。

zip() 与 * 操作符一起可以用来 unzip 一个列表:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

以前,zip() 要求至少一个参数,且 zip() 抛出一个 TypeError 异常,而不是一个空的列表。


官方英文文档引用:

zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:

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)

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip([iter(s)]n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

zip() in conjunction with the * operator can be used to unzip a list:

>> x = [1, 2, 3]
>> y = [4, 5, 6]
>> zipped = zip(x, y)
>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>> x2, y2 = zip(*zip(x, y))
>> x == list(x2) and y == list(y2)

results matching ""

    No results matching ""