Enumerate () descriptionEnumerate () is a Python built-in function enumerate the dictionary is enumerated, enumerated meaning for an iterative (iterable)/Ergodic object (such as lists, strings), enumerate it into an index sequence, It allows both index and value enumerate to be used for counting in the For loop
For example, for a seq, get:
(0, Seq[0]), (1, seq[1]), (2, seq[2])
1 Enumerate () Returns a enumerate object, for example:
enumerate () usingIf you have a list that traverses both the index and the elements, you can first write this:
List1 = ["This", "yes", "one", "test"] for
I in range (len (list1)):
print I, List1[i]
1 2 3 The above method is somewhat cumbersome, using enumerate () will be more direct and graceful:
List1 = ["This", "yes", "one", "test"] for
index, item in enumerate (LIST1):
print Index, item
>>>
0 This
1 is
21
3 tests.
1 2 3 4 5 6 7 8 Enumerate can also receive a second parameter that specifies the starting value of the index, such as:
List1 = ["This", "yes", "one", "test"] for
index, item in enumerate (List1, 1):
print Index, item
>>>
1 This
2 is
31
4 test
1 2 3 4 5 6 7 8
Supplements
If you want to count the number of rows in a file, you can write this:
Count = Len (open (filepath, ' R '). ReadLines ())
1
This method is simple, but it may be slow, and even when the file is large, it won't work.
You can use enumerate ():
Count = 0
for index, line in enumerate (open (filepath, ' R ')):
count = 1