1. 基本功能
zip()
用于将多个可迭代对象(如列表、元组等)的对应元素打包成元组,返回一个迭代器。若可迭代对象长度不同,以最短的为准。
示例:
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
print(list(zipped)) # 输出: [(1, 'a'), (2, 'b'), (3, 'c')]
2. 并行迭代
zip()
常用于同时遍历多个列表:
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
输出:
Alice: 85
Bob: 92
Charlie: 78
3. 创建字典
结合dict()
可将两个列表合并为字典:
keys = ['name', 'age', 'gender']
values = ['Alice', 25, 'Female']
dictionary = dict(zip(keys, values))
print(dictionary) # 输出: {'name': 'Alice', 'age': 25, 'gender': 'Female'}
4. 解压缩
使用*
操作符解压已打包的数据:
zipped = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
names, scores = zip(*zipped)
print(names) # 输出: ('Alice', 'Bob', 'Charlie')
print(scores) # 输出: (85, 92, 78)
5. 处理不等长迭代对象
默认以最短的迭代对象为准,但可通过itertools.zip_longest
填充缺失值:
from itertools import zip_longest
list1 = [1, 2]
list2 = ['a', 'b', 'c']
result = list(zip_longest(list1, list2, fillvalue='x'))
print(result) # 输出: [(1, 'a'), (2, 'b'), ('x', 'c')]
6. 转置矩阵
zip(*matrix)
可快速转置矩阵:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
print(transposed) # 输出: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
注意事项
zip()
返回的是迭代器,需用list()
或循环访问内容。- 严格模式(
strict=True
)要求所有可迭代对象长度一致,否则抛出ValueError
。