关于python中的enumerate函数的应用

≡放荡痞女 提交于 2020-01-02 01:41:29

在python中的enumerate函数是用来遍历列表
用法如下:
lst = [1,2,3]
for index,item in enumerate(lst ):
    print '%d : %s' % (index,item)
这里index对应的是列表lst 中的序号,而item则对应列表lst 中的元数。

 

 

另外:

python enumerate 用法 | 在for循环中得到计数

参数为可遍历的变量,如 字符串,列表等;
返回值为enumerate类:

import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)

输出为:

abcdefghij
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]

在同时需要index和value值的时候可以使用 enumerate。

enumerate 实战

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])
    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'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!