博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于python中的enumerate函数的应用
阅读量:7043 次
发布时间:2019-06-28

本文共 904 字,大约阅读时间需要 3 分钟。

在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 strings = string.ascii_lowercasee = enumerate(s)print sprint 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'))

转载于:https://www.cnblogs.com/zhangjing0502/archive/2012/06/04/2534250.html

你可能感兴趣的文章
Android蓝牙的基本介绍与实现
查看>>
正则表达式和扩展正则表达式
查看>>
keepalived + nginx
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
yum命令
查看>>
iunx下lamp经典组合平台源码安装
查看>>
(ext2,ext3,reiserfs,xfs,jfs)文件系统的性能测试
查看>>
tree
查看>>
c/c++笔记(不断更新)
查看>>
Linux的目录
查看>>
RMAN命令简解
查看>>
Linux 磁盘管理及基础命令使用
查看>>
FormsAuthentication.SetAuthCookie是必须写的吗?
查看>>
mysql编译报错
查看>>
Linux逻辑卷
查看>>
MySQL避免使用SWAP
查看>>
scp非交互式
查看>>
Cobbler全自动批量安装部署Linux系统
查看>>
Solaris 10 开启SSH
查看>>