簡單瞅瞅Python zip()函數

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}