zip in python

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)

Two applications:

  1. cycle
for i, j in zip(a, b):
    print(i, j)
1 4
2 5
3 6
  1. Scramble data
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)

Guess you like

Origin blog.csdn.net/w112348/article/details/114181813
Recommended