Python built-in function - zip

describe

The zip function can "compress" multiple sequences (lists, tuples, dictionaries, sets, strings, and lists of range() intervals) into a zip object. The so-called "compression" is actually to recombine the elements in the corresponding positions in these sequences to generate new tuples one by one. If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object, and the tuple can be decompressed into a list by using the * operator.

grammar

zip([iterable, …], [iterable, …])

parameter explanation

[iterable, …], [iterable, …]: represent one or more iterators

example

Example 1 zip compresses multiple lists

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]

Example 2 zip compresses multiple strings

>>>strs1 = "flower"
>>>strs2 = "flow"
>>>strs3 = "flight"
>>>print(list(zip(strs1, strs2)))
>>>print(list(zip(strs2, strs3)))
[('f', 'f'), ('l', 'l'), ('o', 'o'), ('w', 'w')]
[('f', 'f'), ('l', 'l'), ('o', 'i'), ('w', 'g')]

Example 3 zip(*)

>>>strs = ["flower", "flow", "flight"]
>>>print(list(zip(*strs))) 
[('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')]

Example 4 Use zip(*) to return the maximum value of each column of the matrix

# 返回矩阵的行列最大值
grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
rowMax = list(map(max, grid))  #返回[8,7,9,3]
colMax = list(map(max, zip(*grid)))  #返回[9,4,8,7]

The map function uses

Guess you like

Origin blog.csdn.net/LiuXF93/article/details/121903741