zip
函数是 Python 中的一个内置函数,用于将多个可迭代对象(如列表、元组等)的元素配对,生成一个迭代器。
使用 zip
函数的好处之一就是能够节省内存空间,因为该函数会创建惰性生成器,每次遍历时只生成一个元组。
本篇文章介绍zip
函数的基本用法。
文章目录
1. 使用示例
1.1 配对两个相同长度的列表
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped)) # 输出:[(1, 'a'), (2, 'b'), (3, 'c')]
1.2 匹配不同长度的可迭代对象
如果可迭代对象的长度不同,zip 会以最短的可迭代对象为准:
list1 = [1, 2, 3]
list2 = ['a', 'b']
zipped = zip(list1, list2)
print(list(zipped)) # 输出:[(1, 'a'), (2, 'b')]
如果想要按最长的那个迭代器来生成元组,可以使用 itertools.zip_longest
函数。
def zip_longest_test():
"""
zip_longest 函数的使用
"""
names = ["Alice", "Bob", "Charlie", "David", "Eve"]
counts = [len(n) for n in names]
# 去掉counts的最后一个元素
counts.pop()
for name, count in zip_longest(names, counts):
print(name, count)
if __name__ == "__main__":
zip_longest_test()
输出:
Alice 5
Bob 3
Charlie 7
David 5
Eve None
1.3 解压缩元组成多个可迭代对象
可以使用 zip(*zipped)
来解压已压缩的数据:
zipped = [(1, 'a'), (2, 'b'), (3, 'c')]
list1, list2 = zip(*zipped)
print(list1) # 输出:(1, 2, 3)
print(list2) # 输出:('a', 'b', 'c')
1.4 匹配三个及以上的可迭代对象
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False, True]
zipped = zip(list1, list2, list3)
print(list(zipped)) # 输出:[(1, 'a', True), (2, 'b', False), (3, 'c', True)]
2. 使用场景
2.1 并行迭代两个可迭代对象
有时候,我们想要在一个 for
循环当中迭代两个列表。这时使用zip
函数可以使代码更加简洁。
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")
2.2 数据配对构造字典
keys = ['name', 'age', 'gender']
values = ['Alice', 25, 'Female']
data = dict(zip(keys, values))
print(data) # 输出:{'name': 'Alice', 'age': 25, 'gender': 'Female'}
2.3 矩阵转置
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)]