【python笔记】使用zip函数迭代多个可迭代对象

入门使用

# 示例代码
warframe = ["saryn", "wisp", "volt"]
counts = [len(n) for n in warframe]

for i,j in zip(warframe,counts):
    print(f"name is {i}, len is {j}")
    
# name is saryn, len is 5
# name is wisp, len is 4
# name is volt, len is 4

每次循环时,zip函数会从迭代器里获取各自的下一个元素,并把这些值放在一个元组里面。而这个元组可以拆分到 for 语句里的变量中。

处理迭代元素数量不一致问题

如果两个可迭代元素数量不一致,那么只要其中任何一个迭代器遍历结束,zip函数就会终止。

warframe = ["saryn", "wisp", "volt"]
fans = [10,20,30,40]
for i,j in zip(warframe,fans):
    print(i,j)
# saryn 10
# wisp 20
# volt 30

这时候应该换用zip_longest函数,它封装在itertools模块中。

from itertools import zip_longest
for i,j in zip_longest(warframe,fans):
    print(i,j)
# saryn 10
# wisp 20
# volt 30
# None 40

迭代更多可迭代对象

warframe = ["saryn", "wisp", "volt"]
counts = [len(n) for n in warframe]
fans = [10,20,30,40]

for i,j,k in zip(warframe,counts,fans):
    print(i,j,k)

# saryn 5 10
# wisp 4 20
# volt 4 30
posted @ 2022-02-24 10:01  花酒锄作田  阅读(72)  评论(0编辑  收藏  举报