Pyhont:内建函数enumerate

1、enumerate的中文意思

2、enumerate参数为可遍历的变量,如字符串、列表等,其返回值为enumerate类。

3、enumerate多用在for循环中得到计数 。

[注]:若在for循环中同时需要index和value值,则此时可以考虑enumerate

4、enumerate的使用效果

1 list=['Tom','Jack','Dick','Ellen','Tommas']
2 for item in enumerate(list):
3     print(item)

5、enumerate的使用技巧

a、如果在一个列表中,在遍历列表的同时需要列表的索引,可以这样写:

1 list=['Tom','Jack','Dick','Ellen','Tommas']
2 for item,value in enumerate(list):
3     print(item,value)

b、enumerate可以索引的开始值

1 list=['Tom','Jack','Dick','Ellen','Tommas']
2 for item,value in enumerate(list,1):#指定索引值从1开始
3     print(item,value)

c、读取文件行数

1 count=0
2 for index,value in enumerate(open(filename,'r')):
3     count++
4 
5 print(count) #文件的行数

 

参考:Python脚本之家

posted on 2017-08-12 02:20  Tom文星  阅读(239)  评论(0编辑  收藏  举报

导航