简单瞅瞅Python-zip函数

13次阅读

共计 832 个字符,预计需要花费 3 分钟才能阅读完成。

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}

正文完
 0