zoukankan      html  css  js  c++  java
  • 跟着文档学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
  • 相关阅读:
    2019年6月4号总结
    2019年5月21号总结
    2019年5月8号总结
    2019年5月6号总结
    2019年5月5号总结
    2019年4月18号总结
    java错误笔记之判断字符知否为空出错
    错误笔记:静态方法不能实例化,直接用类名.方法名调用
    Thymeleaf中"th:each""th:if"的用法解析
    @ResponseBody 表示返回的是josn
  • 原文地址:https://www.cnblogs.com/cuixiaochen/p/5379674.html
Copyright © 2011-2022 走看看