Python enumerate index iteration code parsing, pythonenumerate
This article focuses on Python enumerate index iteration.
Index Iteration
In Python, iterations always extract the element itself, not the element index.
For ordered sets, the elements are indeed indexed. Sometimes, we really want to get the index in the for loop. What should 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 - Adam1 - Lisa2 - Bart3 - Paul
Using the enumerate () function, we can bind both the index and element name in the for loop. However, this is not a special Syntax of enumerate. In fact, the enumerate () function treats:
['Adam', 'Lisa', 'Bart', 'Paul']
It becomes similar:
[(0, 'Adam'), (1, 'Lisa'), (2, 'Bart'), (3, 'Paul')]
Therefore, each element of 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:
for index, name in enumerate(L):print index, '-', name
This not only simplifies the code, but also removes two value assignment statements.
It can be seen that index iteration does not really access by index. Instead, the enumerate () function automatically converts each element to a tuple such as index and element, and then iterates, both the index and the element itself are obtained.
Summary
The above is all about parsing the Python enumerate index iteration code. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!