Original link: https://blog.aeilot.top/2023/08/11/python-zip-enumerate/
Recently, I want to use Python to do some small projects and record some learning experience. And if this blog does not update technical articles, it will become a literary blog, which is obviously contrary to the original intention ()
zip()
zip()
function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return an object composed of these tuples.
1 |
>>> a = [ 1 , 2 , 3 ] |
One way to apply this is when traversing, you can traverse multiple arrays at the same time:
1 |
>>> for i, j, k in zip (a, b, c): |
If the lengths of the arrays are not equal, the shortest length will prevail.
If you want to follow the longest length, you can use another function zip_longest()
, so I won’t go into details.
enumerate()
enumerate()
function is used to combine a traversable data object (such as a list, tuple, or string) into an index sequence, listing the data and the index at the same time.
1 |
>>> seasons = [ 'Spring' , 'Summer' , 'Fall' , 'Winter' ] |
This can also be used while traversing.
Precautions
When using these two functions, you need to import the module itertools
, otherwise an error will be reported.
This article is transferred from: https://blog.aeilot.top/2023/08/11/python-zip-enumerate/
This site is only for collection, and the copyright belongs to the original author.