Python中的zip()函数:用法及其应用场景
发布时间:2023-05-22 14:07:10
Zip()是Python中一种内置函数,用于同时遍历多个可迭代对象(列表,元组等),并将每个对象的对应元素组合成元组。Zip功能可用于各种操作,如数据压缩,创建字典等。下面是Zip()函数的用法及其应用场景。
使用方法
Zip()函数的完整语法格式为:
zip(*iterables)
其中参数 *iterables 代表一个或多个可迭代对象。
示例代码:
a = [1, 2, 3] b = ['a', 'b', 'c'] c = ['x', 'y', 'z'] zipped = zip(a, b, c) print(list(zipped))
执行结果:
[(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]
应用场景
1.并行迭代
Zip功能常用于同时遍历多个迭代器,从而实现并行迭代。可使用列表解析式将每个元素以相应方式处理,实现类似于MapReduce的操作。例如:
prices = [10, 20, 30]
names = ['orange', 'banana', 'apple']
for price, name in zip(prices, names):
print(f'{name} costs {price} cents.')
执行结果:
orange costs 10 cents. banana costs 20 cents. apple costs 30 cents.
2.数据压缩
Zip可用于数据压缩,即同时组合多个列表中的元素,并以元组的形式返回结果。例如:
category = ['fruit', 'vegetable', 'meat'] values = [10, 20, 30] data = list(zip(category, values))
执行结果:
[('fruit', 10), ('vegetable', 20), ('meat', 30)]
3.字典创建
Zip可用于同时创建多个字典,其中每个字典用一组迭代器中的元素作为键和值。例如:
keys = ['name', 'age', 'sex'] values = ['Tom', 25, 'male'] my_dict = dict(zip(keys, values))
执行结果:
{'name': 'Tom', 'age': 25, 'sex': 'male'}
4.转置二维数组
Zip可用于将这样列表的行转换为列:
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] transposed = list(zip(*array)) print(transposed)
执行结果:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
在这个例子中,zip(* array)实际上是将列表中的数据分解为三个可迭代对象进行并行迭代。
总结
Zip()函数可用于实现并行迭代,数据压缩,字典的创建和二维数组的转置等操作。Zip可用于多种场景,并且在Python中使用非常广泛。
