Python enumerate usage, pythonenumerate
A new built-in function,Enumerate (), Will make certain loops a bit clearer.enumerate(thing), WhereThingIs either an iterator or a sequence, returns a iterator that will return(0, thing [0]),(1, thing [1]),(2, thing [2]), And so forth.
A common idiom to change every element of a list looks like this:
Usage: it can be used when both index and value are required.
Line = [1, 3, 'dfd ', 'jdjfjd'] for I in range (len (line): item = line [I] print (I, "---> ", item) # running result: 0 ---> 11 ---> 32 ---> dfd3 ---> jdjfjd
It is equivalent to the following code:
line = [1,3,'dfd','jdjfjd']for i,item in enumerate(line): print(i,"-------",item)
Enumerate practice
Line is a string containing 0 and 1. We need to find out all 1:
# Method 1 def read_line (line): sample = {} n = len (line) for I in range (n): if line [I]! = '0': sample [I] = int (line [I]) return sample # method 2 def xread_line (line): return (idx, int (val )) for idx, val in enumerate (line) if val! = '0') print read_line ('123') print list (xread_line ('123 '))