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

    zip有拉链的意思,zip函数像拉链一样将0个或多个可迭代对象按相同位置组合成一个zip对象,该zip对象的每个元素是由每个可迭代对象的相同位置的元素组成的元祖。

    如果zip中有多个序列,而各序列的长度不同,那么返回的对象的长度以最短为准,超出的部分不返回。

    如果zip中只有一个序列,则返回对象的每个元祖中只有一个元素。如果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. 
    
    >>> a = [1,2,3]
    >>> b = [4,5,6]
    >>> c = [7,8,9,10]
    
    >>> zip(a,b)
    <zip object at 0x00000000027D2FC8>
    >>> z=zip(a,b)
    >>> print(z)
    <zip object at 0x00000000027D6088>
    
    >>> for i in z:
    ... 	print(i)
    ... 
    (1, 4)
    (2, 5)
    (3, 6)
    
    >>> x=zip(a)
    >>> for i in x:
    ... 	print(i)
    ... 
    (1,)
    (2,)
    (3,)
    
    >>> y=zip(a,b,c)
    >>> for i in y:
    ... 	print(i)
    ... 
    (1, 4, 7)
    (2, 5, 8)
    (3, 6, 9)
    

    另外zip函数可以使用星号解开zip对象,即unzip。

    zip() in conjunction with the * operator can be used to unzip a list.
    
    >>> m=zip(*zip(a,b,c))
    >>> for i in m:
    ... 	print(i)
    ... 
    (1, 2, 3)
    (4, 5, 6)
    (7, 8, 9)
    

    参考:https://docs.python.org/3/library/functions.html#zip

  • 相关阅读:
    Cron表达式,springboot定时任务
    go 语言中windows Linux 交叉编译
    SSM框架处理跨域问题
    golang gin解决跨域访问
    关于Integer类的值使用==比较
    IoC注解
    spring基础知识
    SQL SERVER大话存储结构(3)_数据行的行结构
    SQL SERVER
    MySQL-记一次备份失败的排查过程
  • 原文地址:https://www.cnblogs.com/keithtt/p/7639167.html
Copyright © 2011-2022 走看看