简单瞅瞅Python zip()函数

发布时间:2019-10-10 09:16:57编辑:auto阅读(1461)

    zip()函数,其实看help(zip)即可

    | Return a zip object whose .__next__() method returns a tuple where
    | the i-th element comes from the i-th iterable argument. The .__next__()
    | method continues until the shortest iterable in the argument sequence
    | is exhausted and then it raises StopIteration.

    返回一个zip对象,其.__ next __()方法返回一个元组,其中第 i 个元素分别来自各可迭代对象的第 i 个参数。.__ next __()方法一直持续到参数序列中最短的iterable(可迭代对象)耗尽,然后它抛出StopIteration

    翻译成正经话就是:
    zip()函数将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
    如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

    注:zip方法在Python2Python3中的不同:在Python 3.x中为了减少内存,zip()返回的是一个对象。如需转换为列表,需使用内置函数list()转换。

    这里简单列一下zip()函数的例子:

    >>> dict([(1, 4), (2, 5), (3, 6)])
    {1: 4, 2: 5, 3: 6}
    >>> a = [1,2,3]
    >>> b = [4,5,6]
    >>> c = [4,5,6,7,8]
    >>> zip(a,b)
    <zip object at 0x7f6bd7e7b648>
    >>> for i in zip(a,b):
        print(i)
    
    (1, 4)
    (2, 5)
    (3, 6)
    >>> list(zip(a,c))    # 打包为元组的列表,元素个数与最短的列表一致
    [(1, 4), (2, 5), (3, 6)]
    >>> dict(zip(a, c))   # 也可以转换为字典
    {1: 4, 2: 5, 3: 6}

关键字