Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hàm zip() trong Python - Gộp nhiều iterator


zip(*iterables) gộp các iterable thành iterator của tuple, phần tử i chứa phần tử thứ i của từng iterable. Dừng ở iterable ngắn nhất.

Ví dụ cơ bản

names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]

zipped = list(zip(names, ages))
print(zipped)  # [('Harry', 19), ('Emma', 20), ('John', 18)]

Unzip (ngược lại)

zipped = [('Harry', 19), ('Emma', 20), ('John', 18)]
new_names, new_ages = zip(*zipped)
print(new_names)  # ('Harry', 'Emma', 'John')
print(new_ages)   # (19, 20, 18)

Duyệt song song (Common use case)

for name, age in zip(names, ages):
    print(f"{name}'s age is {age}")

# Harry's age is 19
# Emma's age is 20
# John's age is 18

zip với số lượng iterable khác nhau

a = [1, 2, 3]
b = ['x', 'y']
c = [10, 20, 30, 40]

print(list(zip(a, b)))        # [(1, 'x'), (2, 'y')] - dừng ở b (len=2)
print(list(zip(a, b, c)))     # [(1, 'x', 10), (2, 'y', 20)]

zip_longest (itertools) - Giữ dài nhất

from itertools import zip_longest
print(list(zip_longest(a, b, fillvalue=None)))
# [(1, 'x'), (2, 'y'), (3, None)]

Ứng dụng thực tế

  • Tạo dict từ 2 list: dict(zip(keys, values))
  • Matrix transpose: list(zip(*matrix))
  • Parallel iteration trong data processing.

Kết luận

zip() là công cụ chuẩn để gộp/duyệt song song iterable. Nhớ nó trả về iterator (lazy), dùng list() nếu cần materialize. Dùng zip_longest khi cần giữ tất cả phần tử.