zip()函数使用

只愿长相守 提交于 2020-02-06 15:54:11

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

我们可以使用 list() 转换来输出元组列表, dict()转换来输出字典。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

 

示例一

 1 >>>a = [1,2,3]
 2 >>> b = [4,5,6]
 3 >>> c = [4,5,6,7,8]
 4 >>> zipped = zip(a,b)     # 返回一个对象
 5 >>> zipped
 6 <zip object at 0x103abc288>
 7 >>> list(zipped)  # list() 转换为列表
 8 [(1, 4), (2, 5), (3, 6)]
 9 >>> list(zip(a,c))              # 元素个数与最短的列表一致
10 [(1, 4), (2, 5), (3, 6)]
11  
12 >>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
13 >>> list(a1)
14 [1, 2, 3]
15 >>> list(a2)
16 [4, 5, 6]
17 >>>
View Code

 

示例二--dict()

 1 tlists = [("a", 1, "xx"), ("b", 2, "yy"), ("c", 3, "zz")]
 2 names = 'kind price unit'.split()
 3 
 4 lst = []
 5 for t in tlists:
 6     lst_dict = dict(zip(names, t))
 7     lst.append(lst_dict)
 8 #lst = [dict(zip(names, t)) for t in tlists] #result as for ↑
 9 for item in lst:
10     print(item)
View Code

输出:

1 {'kind': 'a', 'price': 1, 'unit': 'xx'}
2 {'kind': 'b', 'price': 2, 'unit': 'yy'}
3 {'kind': 'c', 'price': 3, 'unit': 'zz'}
View Code

 

示例二--list()

 1 tlists = [("a", 1, "xx"), ("b", 2, "yy"), ("c", 3, "zz")]
 2 names = 'kind price unit'.split()
 3 
 4 lst = []
 5 for t in tlists:
 6     lst_dict = list(zip(names, t))
 7     lst.append(lst_dict)
 8 #lst = [list(zip(names, t)) for t in tlists] #result as for ↑
 9 for item in lst:
10     print(item)
View Code

输出:

1 [('kind', 'a'), ('price', 1), ('unit', 'xx')]
2 [('kind', 'b'), ('price', 2), ('unit', 'yy')]
3 [('kind', 'c'), ('price', 3), ('unit', 'zz')]
View Code

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!