New contact with a function enumrate, in many cases we want to get an iterative container (such as dict, list, tuple, etc.) elements, want to get a serial number for his use.
Code is often written like this.
List_a = ["Apple", "Dell", "HP", "IBM"]for idx in range (len (list_a)): print ("Idx={0}, Content={1}". Format (IDX, list_ A[IDX]))
If it's dict, it'll be written like this.
Dict_a={"A": "Apple", "B": "Banana", "O": "orange"}IDX = 0for it in dict_a: idx = idx + 1 print ("key[{0}]={1},idx={2 } ". Format (it, Dict_a[it], idx))
But the function has, beautiful poor
It's time for enumrate to play. The Enumrate function can return both the element and the index number. The above two examples can be written like this
List_a = ["Apple", "Dell", "HP", "IBM"]for Idx,val in Enumerate (list_a): print ("Idx={0}, Content={1}". Format (IDX, val))
and the output is
Idx=0, Content=apple
Idx=1, Content=dell
idx=2, CONTENT=HP
Idx=3, CONTENT=IBM
And Dict can write like this.
For Idx,key in Enumerate (dict_a): print ("key[{0}]={1},idx={2}". Format (KEY,DICT_A[KEY],IDX))
Output to
Key[b]=banana,idx=0
Key[o]=orange,idx=1
key[a]=apple,idx=2
In addition, learn how other bloggers use
If you want to count the number of lines in a file, you can write:
Count = Len (open (filepath, ' R '). ReadLines ())
This method is simple, but may be slow, and cannot even work when the file is larger.
You can use enumerate ():
Count = 0for index, line in enumerate (open (filepath, ' R ')): count + = 1
Python enumrate use