python中enumerate函数用法实例分析,pythonenumerate
python中enumerate函数用法实例分析,pythonenumerate
本文实例讲述了python中enumerate函数用法。分享给大家供大家参考。具体分析如下:
今日发现一个新函数 enumerate 。一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:
for i in range (0,len(list)): print i ,list[i]
但是这种方法有些累赘,使用内置enumerrate函数会有更加直接,优美的做法,先看看enumerate的定义:
def enumerate(collection): 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' i = 0 it = iter(collection) while 1: yield (i, it.next()) i += 1
enumerate会将数组或列表组成一个索引序列。使我们再获取索引和索引内容的时候更加方便如下:
for index,text in enumerate(list)): print index ,text
在cookbook里介绍,如果你要计算文件的行数,可以这样写:
count = len(open(thefilepath,'rU').readlines())
前面这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作,下面这种循环读取的方法更合适些。
Count = -1 For count,line in enumerate(open(thefilepath,'rU')): Pass Count += 1
希望本文所述对大家的python程序设计有所帮助。
相关内容
- Python中title()方法的使用简介,pythontitle
- python网络编程之文件下载实例分析,
- Python中zfill()方法的使用教程,pythonzfill
- 在Python中处理字符串之isdecimal()方法的使用,pythonisde
- python对数组进行反转的方法,python数组反转
- Python中列表的一些基本操作知识汇总,python基本操作
- python操作mongodb根据_id查询数据的实现方法,mongodb_id
- 简单介绍Python2.x版本中的cmp()方法的使用,python2.xcmp
- 在Python中操作列表之List.append()方法的使用,pythonlist.
- Python中List.count()方法的使用教程,pythonlist.count
评论关闭