Example Analysis of enumerate function usage in python
This example describes how to use the enumerate function in python. Share it with you for your reference. The specific analysis is as follows:
A new function enumerate was found today. In general, if you want to traverse both the index and element of a list or array, write as follows:
?
1 2 |
For I in range (0, len (list )): Print I, list [I] |
However, this method is somewhat cumbersome. It is more straightforward and elegant to use the built-in enumerrate function. Let's take a look at the definition of enumerate:
?
1 2 3 4 5 6 7 |
Def enumerate (collection ): 'Generates an indexed series: (0, coll [0]), (1, coll [1])...' I = 0 It = iter (collection) While 1: Yield (I, it. next ()) I + = 1 |
Enumerate combines an array or list into an index sequence. This makes it easier to obtain the index and index content as follows:
?
1 2 |
For index, text in enumerate (list )): Print index, text |
In cookbook, if you want to calculate the number of lines in the file, you can write it as follows:
?
1 |
Count = len (open (thefilepath, 'ru '). readlines ()) |
The preceding method is simple, but may be slow. When the file is large or cannot work, the following method is more suitable for reading cyclically.
?
1 2 3 4 |
Count =-1 For count, line in enumerate (open (thefilepath, 'ru ')): Pass Count + = 1 |
I hope this article will help you with python programming.