您的位置:首页 > 编程语言 > Python开发

python效率提升专题-循环

2014-04-01 17:19 246 查看
Author:zhangbo2012@outlook.com

本案例使用三种方法遍历一个列表,并生成新列表。

方法说明
A使用for循环遍历列表中的每一个元素,并插入到新列表中
B使用构造列表法创建新列表
C使用map方法创建新列表
测试代码如下:

import time
oldstr = "football" * 1000000
oldlist = [x for x in oldstr]

def loopA():
newlist = []
t = time.time()
for word in oldlist:
newlist.append(word.upper())

print "method A cost:%.3fs" % (time.time()-t)
del newlist

def loopB():
t = time.time()
newlist = [x.upper() for x in oldlist]
print "method B cost:%.3fs" % (time.time()-t)
del newlist

def loopC():
t = time.time()
newlist = map(str.upper, oldlist)
print "method C cost:%.3fs" % (time.time()-t)
del newlist

loopA()
loopB()
loopC()

测试结果如下:





从结果数据可以看出使用map方法遍历效率最高。而使用for循环的效率最低下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: