「zip()是一个内置函数,它接受一个或多个可迭代项作为输入。它返回一个对象,该对象包含基于索引映射的输入可迭代项的元素。简单的理解就是将不同的元素重新按照一定顺序排序并返回一个元组。数据结构是可以改变的。」
简单示例
list_1 = [1,2,3] list_2 = [4,5,6] list_3 = [7,8,9] for zips in zip(list_1,list_2,list_3): print(zips) """ (1, 4, 7) (2, 5, 8) (3, 6, 9) """
常见的用法列表变成字典
strs = ["flower","flow","flight"] strs1 = ["name","name1"] a = dict(zip(strs1,strs)) print(a) """ {'name': 'flower', 'name1': 'flow'} """
起关键作用的还是dict,普通的zip只能进行类似于取值排序的作用
strs = ["flower","flow","flight"] strs1 = ["name","name1"] a = zip(strs1,strs) print(a.__next__())
「('name', 'flower')这是迭代取值,如果是zip(strs1,strs),得到的是zip类。迭代一次 取一次值,顺序根据strs1,strs先后然后上下进行」
zip与*
strs = ["flower","flow","flight"] a1 = zip(*strs) for i in a1: print(i) """('f', 'f', 'f') ('l', 'l', 'l') ('o', 'o', 'i') ('w', 'w', 'g') 有意思的可以发现,默认以最短的字符串长度进行循环输出"""
根据源码示例,zip+range的用法可以很清楚的得到每一个元素的下标值
strs = ["flower","flow","flight"] b = list(zip(*strs,range(5))) print(b) """[('f', 'f', 'f', 0), ('l', 'l', 'l', 1), ('o', 'o', 'i', 2), ('w', 'w', 'g', 3)] """
虽然长度不一样,但是依旧可以看到下标值
strs = ["flower","flow","flight"] ss = list(map(set, zip(*strs))) print(ss) """[{'f'}, {'l'}, {'i', 'o'}, {'w', 'g'}]"""
列表嵌套元组解包
l1,l2 = zip(*[('Aston', 'GPS'), ('Audi', 'Car Repair'), ('McLaren', 'Dolby sound kit') ]) print(l1) print(l2) """ ('Aston', 'Audi', 'McLaren') ('GPS', 'Car Repair', 'Dolby sound kit') """
此处可以理解为先解包再迭代。