Python运维与数据分析

Python enumerate总结

2016-11-15  本文已影响46人  菩提老鹰

enumerate()说明

实例

>>> goods = [['appple',70999],['banaba',2000],['orange',10000]]
>>> type(goods)
<type 'list'>
>>> for index,item in enumerate(goods):
...     print index,item
... 
0 ['appple', 70999]
1 ['banaba', 2000]
2 ['orange', 10000]
>>> for index,item in enumerate(goods):
...     print index,item[0],item[1]
... 
0 appple 70999
1 banaba 2000
2 orange 10000
>>> 

## enumerate可以有第二个参数
>>> for index,item in enumerate(goods,2):
...     print index,item[0],item[1]
... 
2 appple 70999
3 banaba 2000
4 orange 10000
>>> 

特殊说明

文件大小为83M,用python计算文件行数

实际脚本

#!/usr/bin/env python
#-*- coding:utf8 -*-

file = '/usr/local/tomcat/logs/appLog/appLog.2016-11-08.log'


## 方式一,对于文件很大的时候比较慢
#count = len(open(file,'r').readlines())
#print count


## 方式二,相对比较高效
count = 0
for index, line in enumerate(open(file,'r')):
    count += 1

print count

方式一效果

root@pts/0 # time python /tmp/test.py 
56733

real    0m1.973s
user    0m0.051s
sys 0m0.248s

方式二效果

root@pts/0 # time python /tmp/test.py 
56733

real    0m0.076s
user    0m0.034s
sys 0m0.037s
上一篇下一篇

猜你喜欢

热点阅读