Python zip() 函数是一个内置函数,它允许聚合来自两个或多个可迭代对象的元素,例如列表、元组等。它创建一个新的 Tuples 迭代对象,其中每个 Tuples 都包含位于同一索引的原始迭代对象中的项目。
如果我们传递两个不同长度的可迭代对象,那么,项目数量最少的可迭代对象将决定新迭代器的长度。
语法
以下是 Python zip() 函数的语法 -
zip(iterator...)
参数
Python zip() 函数接受单个参数 -
返回值
Python zip() 函数返回一个迭代器对象。
zip() 函数示例
练习以下示例来理解 Python 中 zip() 函数的用法:
示例:使用 zip() 函数
zip() 函数最常见的用途是将两个或多个可迭代对象的元素组合成一个元组列表。在以下示例中,我们将合并两个包含水果及其数量详细信息的列表。
fruits = ["grapes", "orange", "kiwi", "apple", "mango"]
quantity = [25, 30, 35, 20, 15]
newList = list(zip(fruits, quantity))
print("The new list containing both lists:")
print(newList)
当我们运行上述程序时,它会产生以下结果——
The new list containing both lists:
[('grapes', 25), ('orange', 30), ('kiwi', 35), ('apple', 20), ('mango', 15)]
[('grapes', 25), ('orange', 30), ('kiwi', 35), ('apple', 20), ('mango', 15)]
示例:使用 zip() 函数创建词典
除了元组,zip() 函数还可用于创建字典,其中键和值由两个单独的列表提供。在下面的代码中,我们演示了相同的内容。
keyOfDict = ["empId", "designation", "department"]
valOfDict = [121, "developer", "Technology"]
empDetails = dict(zip(keyOfDict, valOfDict))
print("The new dictionary containing both lists:")
print(empDetails)
以下是上述代码的输出 -
The new dictionary containing both lists:
{'empId': 121, 'designation': 'developer', 'department': 'Technology'}
{'empId': 121, 'designation': 'developer', 'department': 'Technology'}
示例:使用 zip() 函数解压缩可迭代对象
我们还可以使用 zip() 函数解压缩值。如果我们将星号“*”与可迭代对象一起传递给 zip() 函数,它将分隔该可迭代对象的元素。在下面的示例中,我们将解压缩名为 “empDetails” 的列表。
empDetails = [("Ansh", 121), ("Shrey", 131), ("Raman", 141)]
names, ids = zip(*empDetails)
print("Displaying the details:")
for emp, empId in zip(names, ids):
print(f"Name: {emp}, ID: {empId}")
上述代码的输出如下 -
Displaying the details:
Name: Ansh, ID: 121
Name: Shrey, ID: 131
Name: Raman, ID: 141
Name: Ansh, ID: 121
Name: Shrey, ID: 131
Name: Raman, ID: 141
示例:使用 zip() 函数并行迭代多个列表
当我们有多个相同长度的列表时,zip() 函数允许我们并行迭代它们,如下面的代码所示。
empDetails = [("Ansh", 121), ("Shrey", 131), ("Raman", 141)]
names, ids = zip(*empDetails)
print("Displaying the details:")
for emp, empId in zip(names, ids):
print(f"{emp} has ID no: {empId}")
以下是上述代码的输出 -
Displaying the details:
Ansh has ID no: 121
Shrey has ID no: 131
Raman has ID no: 141
Ansh has ID no: 121
Shrey has ID no: 131
Raman has ID no: 141