Python中zip()语法实例讲解
程序员文章站
2023-09-19 22:16:53
语法:
zip([iterable, ...])
iterable——一个或多个迭代器
实例:
>>>a = [1,2,3...
语法:
zip([iterable, ...])
iterable——一个或多个迭代器
实例:
>>>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 相反,可理解为解压,返回二维矩阵式 [(1, 2, 3), (4, 5, 6)]
*还有一种情况
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> zip(*a) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>> map(list,zip(*a)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
上一篇: Python开发工具合集