A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing)
, whereis either an iterator or a sequence, returns an iterator that will return (0,[0])
, (1,[1])
, (2,[2])
, and so forth.
A common idiom to change every element of a list looks like this:
Usage: Can be used when both index and value are needed
line = [1,3,'dfd','jdjfjd'] for i in range(len(line)): item = line[i] print(i,"--->",item) #运行结果: ---> 1 ---> 3 ---> dfd ---> jdjfjd
is equivalent to the following code:
line = [1,3,'dfd','jdjfjd'] for i,item in enumerate(line): print(i,"-------",item)
line is a string containing 0 and 1, you need to find 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('0001110101')
print list(xread_line('0001110101'))
The above is the detailed content of Introduction to the practical usage of python learning enumerate. For more information, please follow other related articles on the PHP Chinese website!