使用场景:
1.将两个或多个列表配对
names = ['a', 'b', 'c']
scores = [1, 2, 3]
zipped = zip(names, scores) # 这里打印出来是 <zip object at 0x10fae6940>
zipped_list = list(zipped) # 转换成list才能打印出来(或者使用 for 循环打印)
print(zipped_list)
2. 遍历多个可迭代对象
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
3. 并行处理多个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# 计算每对元素的和
sums = [x + y for x, y in zip(list1, list2)]
print(sums)
4. 创建字典
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']
# 创建字典
dictionary = dict(zip(keys, values))
print(dictionary)
5. 解压元组
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
# 解压元组
list1, list2 = zip(*pairs)
print(list1)
print(list2)
6. 构造矩阵
rows = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
# 转置矩阵
transposed = list(zip(*rows))
print(transposed)
7. 填充缺失值
from itertools import zip_longest
list1 = [1, 2, 3]
list2 = ['a', 'b']
# 使用 zip_longest 填充缺失值
zipped = list(zip_longest(list1, list2, fillvalue='N/A'))
print(zipped)
8. 组合数据进行处理
names = ['Alice', 'Bob']
ages = [25, 30]
cities = ['New York', 'Los Angeles']
# 组合并处理
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age} years old, lives in {city}")