Python USES the zip function to walk through multiple iterator examples at the same time

  • 2020-05-17 05:44:40
  • OfStack

preface

This article mainly introduces how Python can use the zip function to traverse multiple iterators at the same time. The version in this article is Python3, and zip is the built-in function of Python. Without further ado, let's look at the details.

Application, for example,


>>> list1 = ['a', 'b', 'c', 'd']
>>> list2 = ['apple', 'boy', 'cat', 'dog']
>>> for x, y in zip(list1, list2):
  print(x, 'is', y)
#  The output 
a is apple
b is boy
c is cat
d is dog

This makes it very simple to walk through both lists at once, very pythonic!!

Principle that

The zip function in Python3 can encapsulate two or more iterators as generators, which take the next value of that iterator from each iterator and assemble those values into tuples (tuple). Thus, the zip function implements the parallel traversal of multiple iterators.

Pay attention to

If the length of the input iterator is different, then as long as one iterator is traversed, zip will no longer produce tuples, and zip will terminate early, which may lead to unexpected results. If you're not sure if the list that zip encapsulates is the same length, you can use the zip_longest function from the itertools built-in module, which doesn't care if they're the same length.

In Python2, zip is not a generator. It traverses the iterators in parallel, assembles the tuples, and returns the list of the tuples one time in full, which can take up a lot of memory and cause the program to crash. If you are traversing a data-heavy iterator in Python2, it is recommended to use the izip function in the itertools built-in module.

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: