• 跟着文档学python(三):zip (Python function, in 2. Built-in Functions)


    一,函数的文档:

    zip():

    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)
    True
  • 相关阅读:
    [BZOJ3530][SDOI2014]数数
    [Luogu3121][USACO15FEB]审查Censoring
    [BZOJ1212][HNOI2004]L语言
    [Luogu3041][USACO12JAN]视频游戏的连击Video Game Combos
    AC自动机总结
    (三)LDAP 新增用户
    (二) LDAP 安装
    (一)LDAP 简介
    (十三)VMware Harbor 身份验证模式
    loj#2541. 「PKUWC2018」猎人杀
  • 原文地址:https://www.cnblogs.com/cuixiaochen/p/5379674.html
Copyright © 2020-2023  润新知