海印网
海印网

Python 中的 zip

admin数码00

python 的 zip() 函数详解:高效迭代多个可迭代对象

zip() 函数是 Python 中一个强大的工具,用于将多个可迭代对象(例如列表、元组等)组合成一个迭代器。它一次性从每个可迭代对象中取一个元素,并将这些元素打包成元组。当最短的可迭代对象耗尽时,迭代停止。由于 zip() 返回的是一个迭代器,而非列表,因此需要将其转换为列表 (list()) 才能通过索引访问其元素。

Python 中的 zip-第1张图片-海印网

基本用法:

以下示例展示了 zip() 函数的基本用法,将三个列表 fruits、meats 和 vegetables 组合起来:

立即学习“Python免费学习笔记(深入)”;

fruits = ["apple", "orange", "banana", "kiwi", "lemon", "mango"]
meats = ["chicken", "beef", "pork", "duck", "mutton"]
vegetables = ["onion", "carrot", "garlic", "spinach", "eggplant"]

zipped = zip(fruits, meats, vegetables)
print(list(zipped))  # 将迭代器转换为列表以便查看结果
# Output: [('apple', 'chicken', 'onion'), ('orange', 'beef', 'carrot'), ('banana', 'pork', 'garlic'), ('kiwi', 'duck', 'spinach'), ('lemon', 'mutton', 'eggplant')]

# 迭代访问
for fruit, meat, vegetable in zip(fruits, meats, vegetables):
    print(fruit, meat, vegetable)
# Output:
# apple chicken onion
# orange beef carrot
# banana pork garlic
# kiwi duck spinach
# lemon mutton eggplant

登录后复制

嵌套 zip() 的使用:

zip() 函数可以嵌套使用,以处理更复杂的迭代结构。以下示例展示了如何嵌套 zip() 函数,以及如何解包结果:

# 双层嵌套
zipped_nested = zip(zip(fruits, meats), vegetables)
print(list(zipped_nested))
# Output: [(('apple', 'chicken'), 'onion'), (('orange', 'beef'), 'carrot'), (('banana', 'pork'), 'garlic'), (('kiwi', 'duck'), 'spinach'), (('lemon', 'mutton'), 'eggplant')]

for (fruit, meat), vegetable in zip(zip(fruits, meats), vegetables):
    print(fruit, meat, vegetable)
# Output:
# apple chicken onion
# orange beef carrot
# banana pork garlic
# kiwi duck spinach
# lemon mutton eggplant

# 三层嵌套 (更复杂的例子)
fruits = ["Apple", "Orange", "Banana", "Kiwi", "Lemon", "Mango"]
meats = ["Chicken", "Beef", "Pork", "Duck", "Mutton"]
vegetables = ["Onion", "Carrot", "Garlic", "Spinach", "Eggplant"]

zipped_triple = zip(zip(fruits, zip(meats)), vegetables)
print(list(zipped_triple))
# Output: [(('Apple', ('Chicken',)), 'Onion'), (('Orange', ('Beef',)), 'Carrot'), (('Banana', ('Pork',)), 'Garlic'), (('Kiwi', ('Duck',)), 'Spinach'), (('Lemon', ('Mutton',)), 'Eggplant')]

for (fruit, (meat,)), vegetable in zip(zip(fruits, zip(meats)), vegetables):
    print(fruit, meat, vegetable)
# Output:
# Apple Chicken Onion
# Orange Beef Carrot
# Banana Pork Garlic
# Kiwi Duck Spinach
# Lemon Mutton Eggplant

登录后复制

请注意,在嵌套使用 zip() 时,解包元组的方式需要根据嵌套的层数进行调整。 这使得 zip() 函数在处理多个数据源或进行数据转换时非常灵活。

请享用您的咖啡☕

以上就是Python 中的 zip的详细内容,更多请关注其它相关文章!

Tags: 嵌套迭代

Sorry, comments are temporarily closed!