Overview

同時迭代多個 可迭代物件

Usage

測試資料:

a = [0, 1, 2]
b = [3, 4, 5]

建立 Zip

z = zip(a, b)
# <zip object at 0x0000022E1CAECFC8>

建立 List

c = list(zip(a, b))
# [(0, 3), (1, 4), (2, 5)]

建立 Dict

d = dict(zip(a, b))
# {0: 3, 1: 4, 2: 5}

搭配 For 迴圈

for i, j in zip(a, b):
    print(f'i: {i}, j: {j}')
for i, j in dict(zip(a, b)).items():
    print(f'i: {i}, j: {j}')

從 List 復原

k, v = zip(*c)

從 Dict 復原

k, v = zip(*d.items())

矩陣轉置

[list(row) for row in zip(*c)]
# [[0, 1, 2], [3, 4, 5]]