用Python内置的zip函数来实现。这个函数能把两个或更多的iterator封装成惰性生成器(lazy generator)。每次循环时,它会分别从这些迭代器里获取各自的下一个元素,并把这些值放在一个元组里面。
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长度不一致时,最短的遍历完不再遍历,原理:只要其中任何一个迭代器处理完毕,它就不再往下走了。
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
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)