Home > Backend Development > Python Tutorial > Detailed explanation of Python's example of using zip function to traverse multiple iterators at the same time

Detailed explanation of Python's example of using zip function to traverse multiple iterators at the same time

黄舟
Release: 2016-12-15 09:17:04
Original
1512 people have browsed it

Foreword

This article mainly introduces how Python uses the zip function to traverse multiple iterators at the same time. The version in this article is Python3, and the zip function is a built-in function of Python. Not much to say below, let’s look at the detailed content.

Application example

>>> list1 = ['a', 'b', 'c', 'd']
>>> list2 = ['apple', 'boy', 'cat', 'dog']
>>> for x, y in zip(list1, list2):
  print(x, 'is', y)
# 输出
a is apple
b is boy
c is cat
d is dog
Copy after login

This is a very simple way to traverse two lists at the same time, very pythonic! ! !

Principle description

The zip function in Python3 can encapsulate two or more iterators into a generator. This zip generator will get the next value of the iterator from each iterator, and then Assemble these values ​​into tuples. In this way, the zip function traverses multiple iterators in parallel.

Note

If the input iterators are of different lengths, then as soon as one iterator is traversed, zip will no longer generate tuples, and zip will terminate early, which may lead to unexpected results and must not be ignored. If you are not sure whether the lists encapsulated by zip are of equal length, you can use The zip_longest function in the itertools built-in module does not care whether their lengths are equal.

In Python2, zip is not a generator. It traverses these iterators in parallel, assembles tuples, and returns the list of tuples completely at once. This may occupy a lot of memory and cause the program to crash. If you want to traverse an iterator with a large amount of data in Python2, it is recommended to use The izip function in the itertools built-in module.

Summary

The above is the entire content of Python using the zip function to traverse multiple iterators at the same time. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template