python uses zip to iterate over multiple sequence examples simultaneously
- 2021-07-10 20:09:11
- OfStack
This example shows that python uses zip to iterate multiple sequences at the same time. Share it for your reference, as follows:
zip can traverse multiple iterators in parallel
In python 3, zip is equivalent to a generator, which generates Yuan Zu in the traversal process, and python2 generates Yuan Zu well and returns the whole list once
zip(x,y,z)
Generates an iterator that returns tuples (x, y, z)
>>> x = [1, 2, 3, 4, 5]
>>> y = ['a', 'b', 'c', 'd', 'e']
>>> z = ['a1', 'b2', 'c3', 'd4', 'e5']
>>> for i in zip(x,y,z):
... print(i)
...
(1, 'a', 'a1')
(2, 'b', 'b2')
(3, 'c', 'c3')
(4, 'd', 'd4')
(5, 'e', 'e5')
Traversal length is not 1 sample (as long as one is exhausted, it will end. If you want to traverse different lengths, please use zip_longest of itertools)
>>> x = [1, 2, 3, 4, 5, 6]
>>> y = ['a', 'b', 'c', 'd', 'e']
>>> for i in zip(x,y):
... print(i)
...
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')
>>> from itertools import zip_longest
>>> x = [1, 2, 3, 4, 5, 6]
>>> y = ['a', 'b', 'c', 'd', 'e']
>>> for i in zip_longest(x,y):
... print(i)
...
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')
(6, None)
More readers interested in Python can check the topics of this site: "Python Data Structure and Algorithm Tutorial", "Python Function Use Skills Summary", "Python String Operation Skills Summary", "Python Introduction and Advanced Classic Tutorial" and "Python File and Directory Operation Skills Summary"
I hope this article is helpful to everyone's Python programming.