Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@giwa

EP 11 Use `zip` to Process Iterators in Parallel

  • The zip built-in function can be used to iterate over multiple iterators in parallel.
  • In Python 3, zip is a lazy evaluation that produces tuples. In Python 2, zip returns the full result as a list of tuples.
  • zip truncate its outpu silently if you supply it with iterators of different length.
  • The zip_longest function from the itertools built-in module lets you iterate over multiple iterators in parallel regardless of the their lengths.

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
>>>
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?