Summary of Methods for Traversing Lists in Python
- 2021-07-03 00:23:45
- OfStack
There are several ways to traverse lists in Python:
1. for loop traversal
lists = ["m1", 1900, "m2", 2000]
for item in lists:
print(item)
lists = ["m1", 1900, "m2", 2000]
for item in lists:
item = 0;
print(lists)
Run results:
['m1', 1900, 'm2', 2000]
2. while loop traversal:
lists = ["m1", 1900, "m2", 2000]
count = 0
while count < len(lists):
print(lists[count])
count = count + 1
3. Index traversal:
for index in range(len(lists)):
print(lists[index])
4. Use iter ()
for val in iter(lists):
print(val)
5. enumerate traversal method
for i, val in enumerate(lists):
print(i, val)
Run results:
0 m1
1 1900
2 m2
3 2000
You can use the following methods when traversing elements from non-0 subscripts
for i, el in enumerate(lists, 1):
print(i, el)
Run results:
1 m1
2 1900
3 m2
4 2000
Expand
python, the method of traversing files
When doing verification code recognition, you need to compare it with the pictures in the library to find the closest picture, and then you can name it with the characters corresponding to picture 1, get the name of the file, and read out the name of the picture as the verification code. The following are three ways of traversing documents summarized by me through online data. The first one is similar to the second one, but there are some differences between it and the third one.
First to get the path of the folder, I am a folder under the file traversal, need to remove the suffix of the file, Note: num for me to create a folder
lists = ["m1", 1900, "m2", 2000]
for item in lists:
item = 0;
print(lists)
0