A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing)
, whereis either an iterator or a sequence, returns a 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:
用法:同時需要index 和value 值得時候可以使用
line = [1,3,'dfd','jdjfjd'] for i in range(len(line)): item = line[i] print(i,"--->",item) #运行结果: ---> 1 ---> 3 ---> dfd ---> jdjfjd
等價於下列程式碼:
line = [1,3,'dfd','jdjfjd'] for i,item in enumerate(line): print(i,"-------",item)
line 是個string 包含0 和1,要把1都找出來:
#方法一
def read_line(line):
sample = {}
n = len(line)
for i in range(n):
if line[i]!='0':
sample[i] = int(line[i])
## sample[i] = int(line[i])## return sample
## #方法二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'))以上是python學習enumerate實作用法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!