Objective
This article is mainly about how Python uses the zip function to traverse multiple iterators at the same time, and the version in the text is the Python3,zip function, which is a built-in Python function. The following words do not say more, to see the detailed content.
Application examples
>>> List1 = [' A ', ' B ', ' C ', ' d ']
>>> list2 = [' Apple ', ' boy ', ' cat ', ' dog ']
>>> for X, Y in-Zip (List1, list2):
print (x, ' is ', y)
# output ' A is ' Apple B-is boy C-is
cat D is
dog
This makes it very simple to iterate through two lists at the same time, very pythonic!!!
Principle explanation
The zip function in Python3 can encapsulate two or more than two iterators into generators, which get the next value of the iterator from each iterator, and then assemble the values into tuples (tuple). Thus, the zip function implements a parallel traversal of multiple iterators.
Attention
If the input iterator length is different, then, as long as there is an iterator to traverse, the zip will no longer produce tuples, the zip would terminate prematurely, which may lead to unexpected results, should be observed. If you are unsure whether the list encapsulated by the zip is equal, you can instead use the Zip_longest function in the Itertools built-in module, which does not care whether their length is equal or not.
In the Python2, a zip is not a generator, it traverses these iterators in parallel, assembles the tuples, and returns the list of these tuples once and for all, which can consume a lot of memory and cause the program to crash, and if you want to traverse a large number of iterators in Python2, recommend using Itertools the Izip function in the built-in module.
Summarize
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.