Python中的zip方法

2021-10-14 02:14:56 字數 1588 閱讀 2221

zip()python中的乙個內建函式,它接受一系列可迭代物件作為引數,將不同物件中相對應的元素(根據索引)打包成乙個元組tuple,返回乙個zip物件,可以通過listzip物件轉化為list物件。我們來看看zip的函式定義

zip(*iterables) --> zip object

| |  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.

由上述可知,如果傳入的引數的長度不同,元組的個數和傳入引數中最短物件的長度一致

最後來看看幾個示例

in [1]: alist = [1, 2, 3, 4, 5]

in [2]: blist = [5, 4, 3, 2, 1]

in [3]: a = zip(alist)

in [4]: type(a)

out[4]: zip

in [5]: list(a)

out[5]: [(1,), (2,), (3,), (4,), (5,)]

in [6]:

可以看到a的資料型別是zip,然後通過list轉化,就可以看到以元組為元素的列表了。上例中zip函式只有乙個引數,所以元組中也只有乙個元素

in [7]: blist = [5, 4, 3, 2, 1]

in [8]: b = zip(alist, blist)

in [9]: list(b)

out[9]: [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]

in [10]:

當我們給zip傳入2個可迭代引數時,元組中的元素就有2個了

in [16]: clist = [8, 8, 8]

in [17]: alist = [1, 2, 3, 4, 5]

in [18]: c = zip(alist, clist)

in [19]: list(c)

out[19]: [(1, 8), (2, 8), (3, 8)]

in [20]:

上面中的clist只有3個元素,而alist有5個元素,因此,zip物件中的元組個數跟clist的元素個數一樣,都是3個

python中zip函式的使用方法

zip函式接受任意多個 包括0個和1個 序列作為引數,返回乙個tuple列表。1.示例1 x 1,2,3 y 4,5,6 z 7,8,9 xyz zip x,y,z print xyz 執行的結果是 1,4,7 2,5,8 3,6,9 從這個結果可以看出zip函式的基本運作方式。2.示例2 x 1,...

Python中zip函式的使用方法

定義 zip iterable,zip 是python的乙個內建函式,它接受一系列可迭代的物件作為引數,將物件中對應的元素打包成乙個個tuple 元組 然後返回由這些 tuples組成的list 列表 若傳入引數的長度不等,則返回list的長度和引數中長度最短的物件相同。利用 號操作符,可以將lis...

Python基礎(zip方法)

描述 將zip函式中的兩個可迭代物件引數按對應索引值進行匹配組合,得到zip物件。拉鍊式函式 zip函式簡單應用如下 1 zip函式 23 第一種zip引數兩個可迭代物件元素個數相同 4 list1 a b c d e 5 list2 1,2,3,4,5 6 res1 list zip list1,...