python效率提升专题-循环

 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()

测试结果如下:

image

从结果数据可以看出使用map方法遍历效率最高。而使用for循环的效率最低下。

原文地址:https://www.cnblogs.com/zhangbo2012/p/3638753.html