首页 > 编程语言 > 详细

python enumerate 用法

时间:2016-12-13 07:30:17      阅读:189      评论:0      收藏:0      [点我收藏+]

A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing) , where thing is 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:

用法:在同时需要index 和 value 值得时候可以使用

line = [1,3,dfd,jdjfjd]
for i in range(len(line)):
    item = line[i]
    print(i,"--->",item)

#运行结果:
0 ---> 1
1 ---> 3
2 ---> dfd
3 ---> jdjfjd

等价于下列代码:

line = [1,3,dfd,jdjfjd]
for i,item in enumerate(line):
    print(i,"-------",item)

 

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‘))

python enumerate 用法

原文:http://www.cnblogs.com/frankb/p/6166304.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!