用Python内置的zip函数来实现。这个函数能把两个或更多的iterator封装成惰性生成器(lazy generator)。每次循环时,它会分别从这些迭代器里获取各自的下一个元素,并把这些值放在一个元组里面。
1 2 3 4 5 6 7 8 9 10 11 | names = [ "Cecilia" , "Lise" , "Marie" ] counts = [ len (n) for n in names] max_count = 0 for name, count in zip (names, counts): if count > max_count: longest_name = name max_count = count print (longest_name) |
当iterator长度不一致时,最短的遍历完不再遍历,原理:只要其中任何一个迭代器处理完毕,它就不再往下走了。
1 2 3 4 5 6 7 8 9 10 11 12 | names = [ "Cecilia" , "Lise" , "Marie" ] counts = [ len (n) for n in names] max_count = 0 names.append( "Rosalind" ) for name, count in zip (names, counts): if count > max_count: longest_name = name max_count = count print (longest_name) # 输出Cecilia |
长度不一致时如何处理呢?zip_longest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import itertools names = [ "Cecilia" , "Lise" , "Marie" ] counts = [ len (n) for n in names] max_count = 0 names.append( "Rosalind" ) for name, count in itertools.zip_longest(names, counts): if count > max_count: longest_name = name max_count = count print (longest_name) """ 输出:TypeError: '>' not supported between instances of 'NoneType' and 'int' 原因:zip_longest按最长的遍历,其他长度不足的列表会以None代替 """ |
是否可不用None,用特定的值?fillvalue
import itertools
names = ["Cecilia", "Lise", "Marie"]
counts = [len(n) for n in names]
max_count = 0
names.append("Rosalind")
for name, count in itertools.zip_longest(names, counts, fillvalue=0):
if count > max_count:
longest_name = name
max_count = count
print(longest_name)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix