- The zip built-in function can be used to iterate over multiple iterators in parallel.
Effective Python
Verbose
>>> names = "Michel Stonbreaker Peter Bilas Franklin".split()
>>> 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)
Stonbreaker
You can use enumerate. But it is still verbose.
>>> for i, name in enumerate(names):
... count = letters[i]
... if count > max_letters:
... longest_name = names[i]
... max_letters = count
...
>>> print(longest_name)
Stonbreaker
>>> for name, count in zip(names, letters):
... if count > max_letters:
... longest_name = name
... max_letters = count
...
>>> print(longest_name)
Stonbreaker
zip truncate implecitly. if it iterate the different length of iteratable objects.
itertools.zip_longest
could be a solution for this.
>>> for name, count in zip(names, letters):
... print(name, count)
...
Michel 6
Stonbreaker 11
Peter 5
Bilas 5
Franklin 8
>>> from itertools import zip_longest
>>> for name, count in zip_longest(names, letters):
... print(name, count)
...
Michel 6
Stonbreaker 11
Peter 5
Bilas 5
Franklin 8
Matei None
>>>
Recommended Posts