over 3 years ago

Use zip to Process Iterators in Parallel

zip()將傳入的 iterables 打包成 tuples

names = ['Cecilia', 'Lise', 'Marie']
letters = [len(n) for n in names]

longest_name = None
max_letters = 0

for i in range(len(names)):
    count = letters[i]
    if count > max_letters:
        longest_name = names[i]
        max_letters = count

print(longest_name)  # 'Cecilia'

上面的程式可讀性差,可以使用 enumerate()稍微改善一點

longest_name = None
max_letters = 0
for i, name in enumerate(names):
    count = letters[i]
    if count > max_letters:
        longest_name = name
        max_letters = count
print(longest_name)

比較好的作法是用 zip() 或者在 Python 2 建議使用 itertools.izip()

longest_name = None
max_letters = 0
for name, count in zip(names, letters):
    if count > max_letters:
        longest_name = name
        max_letters = count
print(longest_name)

須注意使用 zip()時,iterables 最好長度一樣,多出來的將不予理會,也就是說產生出來的 list 長度為最短的 iterable 的長度。可以使用itertools.zip_longest()來處理不同長度的 iterables。

import itertools

names.append('Tom')
lsit(itertools.izip_longest(names, letters, fillvalue='-'))
# [('Cecilia', 7), ('Lise', 4), ('Marie', 5), ('Tom', '-')]
← Effective Python 心得筆記: Item 10 Effective Python 心得筆記: Item 12 →
 
comments powered by Disqus