描述
zip()
函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
可以使用list()转换来输出列表。
若各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用*
号操作符,可以将元祖解压为列表。
例1
1 2 3 4 5 6 7
| a = [1,2,3] c = [1,2,3,4]
zipped = zip(a,c) l_zipped = list(zipped) b = 3 print(type(zipped),type(l_zipped))
|
输出结果为:
1 2
| <class 'zip'> <class 'list'> [(1, 1), (2, 2), (3, 3)]
|
例2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| a = [ [1,2], [3,4], [5,6] ] c = [ [5,6], [7,8], [9,10] ] zipped = zip(a,c) l_zipped = list(zipped) b = 3 print(type(zipped),type(l_zipped))
print(l_zipped)
|
输出结果:
1 2 3
| <class 'zip'> <class 'list'> [([1, 2], [5, 6]), ([3, 4], [7, 8]), ([5, 6], [9, 10])]
|
例3
1 2 3 4 5 6 7 8 9 10 11 12
| a = [1,2,3] c = [1,2,3,4]
zipped = zip(a,c) print(zipped,type(zipped)) accmulated = 1*[0] accmulated = [x_c[0] + x_c[1] for x_c in zip(a,c)] for i in zipped: print(i,type(i)) l_zipped = list(zipped) # 转换为列表 #print(l_zipped) print("accmulated:",accmulated)
|
输出结果:
1 2 3 4 5
| <zip object at 0x7f3128d8d5c8> <class 'zip'> (1, 1) <class 'tuple'> (2, 2) <class 'tuple'> (3, 3) <class 'tuple'> accmulated: [2, 4, 6]
|
例4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| a = [ [1,2], [3,4], [5,6] ] c = [ [5,6], [7,8], [9,10] ] zipped = zip(a,c) l_zipped = list(zipped) accmulated = 1 *[0] # 注:此处将zip(a,c)换为zipped则显示为空 for i in zip(a,c): print(i,type(i)) accmulated = [x_c[0] + x_c[1] for x_c in zip(a,c)] print("accmulated:",accmulated)
|
输出结果:
1 2 3 4 5
| ([1, 2], [5, 6]) <class 'tuple'> ([3, 4], [7, 8]) <class 'tuple'> ([5, 6], [9, 10]) <class 'tuple'> accmulated: [[1, 2, 5, 6], [3, 4, 7, 8], [5, 6, 9, 10]]
|
例5:矩阵的行列互换
1 2 3
| a = [[1,2,3],[3,4,5]] a1 = zip(*a) print(list(a1))
|
输出结果:
1
| [(1, 3), (2, 4), (3, 5)]
|