This is a built-in function of python. I found it while reading the book. mark it.
When we need to traverse both indexes and elements, we can consider using the enumerate function. The enumerate function accepts an object that can be traversed, such as a list or string.
For example, if we have a list of ["one", "two", "there"], we need to add its number before each element in the list.
Copy codeThe Code is as follows:
I = 0
Seq = ["one", "two", "three"]
For element in seq:
Seq [I] = '% d: % s' % (I, seq [I])
I + = 1
Print seq
['0: one', '1: two', '2: three ']
Using the enumerate function, we can simplify our code and eliminate the need to define temporary variables for counting.
Copy codeThe Code is as follows:
Seq = ["one", "two", "three"]
For I, element in enumerate (seq ):
Seq [I] = '% d: % s' % (I, seq [I])
Print seq
['0: one', '1: two', '2: three ']
The drama is not over yet. The charm of python is here. Let's write a Phthonic script.
Copy codeThe Code is as follows:
Seq = ["one", "two", "three"]
Print ['% d: % s' % (I, element) for I, element in enumerate (seq)]
['0: one', '1: two', '2: three ']
Well, python's traversal technology is very flexible. I can't finish talking about it in a few words. I need to turn off the lights and get my sleep.