在同时需要用到index和value值的时候可以用到enumerate,参数为可遍历的变量,如字符串,列表等,返回enumerate类。
例:
import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)
返回:
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'),
(8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15,
'p'), (16, 'q'), (17, 'r'), (18, 's'), (19, 't'), (20, 'u'), (21, 'v'), (22, 'w
'), (23, 'x'), (24, 'y'), (25, 'z')]
用enumerate将string中的1都找出来,用enumerate实现:
def fun(line):
return ((ids,int(val)) for ids,val in enumerate(line) if val != '0')
print list(fun("000111000111"))
输出结果为:
[(3, 1), (4, 1), (5, 1), (9, 1), (10, 1), (11, 1)]