a = [1, 2, 3]
b = [4, 5, 6]
zipped = list(zip(a, b))
aa, bb = zip(*zipped) # star means unzip
print(zipped)
print(aa, bb)
[(1, 4), (2, 5), (3, 6)]
(1, 2, 3) (4, 5, 6)
两个应用:
- 循环
for i, j in zip(a, b):
print(i, j)
1 4
2 5
3 6
- 打乱数据
import numpy as np
def shuffle(x, y):
zipped = list(zip(x, y))
np.random.shuffle(zipped)
return zip(*zipped)
x, y = [1, 2, 3], [4, 5, 6]
x, y = shuffle(x, y)
print(x)
print(y)
(2, 1, 3)
(5, 4, 6)