python-zip
zip()
是Python的一个内建函数
定义:zip([iterable, ...])
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple
(元组),然后返回由这些tuples组成的list
(列表)。
若传入参数的长度不等,则返回list
的长度和参数中长度最短的对象相同。
传入两个参数
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print(xyz)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
a = ['a', 'b', 'c', 'd']
b = ['1', '2', '3', '4']
result = zip(a, b)
print(list(result))
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
传入一个参数
grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
print(list(zip(grid)))
# [([3, 0, 8, 4],), ([2, 4, 5, 7],), ([9, 2, 6, 3],), ([0, 3, 1, 0],)]
print(list(zip(*grid)))
# [(3, 2, 9, 0), (0, 4, 2, 3), (8, 5, 6, 1), (4, 7, 3, 0)]
输入数据不等长时
grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1]]
print(list(zip(grid)))
[([3, 0, 8, 4],), ([2, 4, 5, 7],), ([9, 2, 6, 3],), ([0, 3, 1],)]
grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1]]
print(list(zip(*grid)))
# [(3, 2, 9, 0), (0, 4, 2, 3), (8, 5, 6, 1)]
对数据排序
names = ['John', 'Amy', 'Jack']
scores = [98, 100, 85] # 分数和名字是一一对应的
data = list(zip(names, scores))
data.sort()
print(data)
[('Amy', 100), ('Jack', 85), ('John', 98)]
data2 = list(zip(scores, names))
data2.sort()
print(data2)
[(85, 'Jack'), (98, 'John'), (100, 'Amy')]
输入数据不等长
输出取决于最短的数据
x = [1, 2, 3]
y = [4, 5, 6, 11]
z = [7, 8, 9, 10]
xyz = zip(x, y, z)
print xyz运行的结果是:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
1 11
2 12
3 13
处理不等长数据可以内置zip_longest
代替
使用itertools
包中的zip_longest
,使用方法如下:
from itertools import zip_longest
a = [1,2,3,4,5,6]
b = [11,12,13]
for i,j in zip_longest(a,b):
print(i,j)
1 11
2 12
3 13
4 None
5 None
6 None
标签:11,zip,python,xyz,list,grid,print
From: https://www.cnblogs.com/tian777/p/17314318.html