Tag:ar using for on art code ad python method
Index iterations
In Python, iterations are always taken out of the element itself, not the index of the element.
For an ordered set, the element is indeed indexed. Sometimes we really want to get the index in the for loop, what do we do?
The method is to use the enumerate () function:
>>> L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
>>> for index, name in enumerate (L):
... print index, '-', name
...
0-adam
1-lisa
2-bart
3-paul
Using the enumerate () function, we can bind both index and element name in the For loop. However, this is not a special syntax for enumerate (). In fact, the enumerate () function puts:
[' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Into something like this:
[(0, ' Adam '), (1, ' Lisa '), (2, ' Bart '), (3, ' Paul ')]
Therefore, each element of an iteration is actually a tuple:
For T in enumerate (L):
index = t[0]
name = T[1]
Print index, '-', name
If we know that each tuple element contains two elements, the for loop can be further abbreviated as:
For index, name in enumerate (L):
Print index, '-', name
This not only makes the code simpler, but also reduces the number of two assignment statements.
It can be seen that the index iteration is not really indexed, but instead the enumerate () function automatically turns each element into a tuple (index, Element) and iterates over the index and the element itself.
Python Enumerate index iterations