Python中一些代码优化的tips
1.拼接字符串的要点
使用“+”进行拼接字符串,每拼接一次,都会生成新的字符串的对象,不推荐使用“+”拼接字符串
使用join函数,配合列表使用效果更好
import time time_01 = time.time() # 起始时刻 a = "" for i in range(10000000): a += "nxr" time_02 = time.time() # 结束时刻 print("总用时:"+str(time_02-time_01)) time_03 = time.time() # 起始时刻
b = []
for i in range(10000000):
b.append("nxr")
"".join(b)
time_04 = time.time() # 结束时刻
print("总用时:"+str(time_04-time_03))
2.循环代码优化
import time """ 循环优化 1.尽量减少内层循环的计算,尽量往外提 2.局部变量查询比较快,尽量使用局部变量 """ start = time.time() for i in range(1000): result = [] for m in range(10000): result.append(i*1000+m*100) end = time.time() print("耗时:{0}".format((end-start))) start = time.time() for i in range(1000): result = [] c = i*1000 # 将计算式子从循环提出来 for m in range(10000): result.append(c+m*100) end = time.time() print("耗时:{0}".format((end-start)))
# 耗时:3.3758254051208496
# 耗时:2.453188896179199
3.对列表进行插入,删除操作时,尽量在列表队尾进行操作,否则会进行数组的拷贝,效率低下。
4.zip(),并行迭代
a = [1,2,3] b = [4,5,6] c = [7,8,9] for i,j,k in zip(a,b,c): print("{0}-{1}-{2}".format(i,j,k))