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
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)!