Python 的 map、列表推导、循环效率比较

话不多说,直接上代码:

1.准备数据(三个列表)

import time

x=[]
x1=[]
x2=[]

for i in range(1000000):
    x.append(i)
    x1.append(i)
    x2.append(i)

2.开始表演

# 2.1.for循环

start1=time.clock()
for i in range(len(x)):
    x[i] += 1
end1=time.clock()
print(end1-start1)  # 1.8428430000000002    # 速度最慢

# 2.2.map函数

start2=time.clock()
y = map(lambda a: a + 1, x1)
end2=time.clock()
print(end2-start2)  # 8.999999999925734e-06  速度最快

# 2.3.列表表达式

start3=time.clock()
y3 = [a + 1 for a in x2]
end3=time.clock()
print(end3-start3)  # 1.210083  速度第二

3.得出结论:V(map) > V(列表推导式) > V(for循环语句)

发现map最快,map返回的是迭代器,如果变成list则花的时间与循环差不多,其次是列表推导,最后是循环来写。



猜你喜欢

转载自blog.csdn.net/liangkaiping0525/article/details/80862385
今日推荐