zoukankan      html  css  js  c++  java
  • Python zip() 函数

    zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

    如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

    Definition and Usage

    The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

    If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.

    zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。

    Syntax

    zip(iterator1, iterator2, iterator3 ...)
     

    Parameter Values

    ParameterDescription
    iterator1, iterator2, iterator3 ... Iterator objects that will be joined together

    Example

    Join two tuples together:

    a = ("John", "Charles", "Mike")
    b = ("Jenny", "Christy", "Monica")

    x = zip(a, b)

    #use the tuple() function to display a readable version of the result:

    print(tuple(x))

    More Examples

    Example

    If one tuple contains more items, these items are ignored:

    a = ("John", "Charles", "Mike")
    b = ("Jenny", "Christy", "Monica", "Vicky")

    x = zip(a, b)


    #use the tuple() function to display a readable version of the result:

    print(tuple(x))

    >>>a = [1,2,3]
    >>> b = [4,5,6]
    >>> c = [4,5,6,7,8]
    >>> zipped = zip(a,b)     # 打包为元组的列表
    [(1, 4), (2, 5), (3, 6)]
    >>> zip(a,c)              # 元素个数与最短的列表一致
    [(1, 4), (2, 5), (3, 6)]
    >>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
    [(1, 2, 3), (4, 5, 6)]
  • 相关阅读:
    LuoguP2763 试题库问题(最大流)
    LuoguP3254 圆桌问题(最大流)
    LuoguP2765 魔术球问题(最大流)
    LuoguP2764 最小路径覆盖问题(最大流)
    LuoguP4016 负载平衡问题(费用流)
    LuoguP2756 飞行员配对方案问题(最大流)
    BZOJ3675: [Apio2014]序列分割(斜率优化Dp)
    BZOJ1814: Ural 1519 Formula 1(插头Dp)
    BZOJ4652: [Noi2016]循环之美(莫比乌斯反演,杜教筛)
    BZOJ4916: 神犇和蒟蒻(杜教筛)
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13791428.html
Copyright © 2011-2022 走看看