1)字典与列表
python中字典—hash table;列表—数组
对成员的查找访问字典比列表快
listtmp=[1,2,3,4]
dicttmp=dict.fromkeys(listtmp,True)
2)集合与列表
set的交并差操作比list迭代快 list(set(lista)&set(list)) | union & intersection – difference
3)python 的条件表达式是lazy evaluation
if x and y: x为false y的值将不再计算
4)字符串优化:对任何字符串的操作都将产生新的对象
(1)字符串连接尽量使用join()而不是+
避免:
s=""
for x in list:
s+=func(x)
代替方法:
sliest = [func(elt) for elt in somelist]
s = "".join(slist)
(2)当对字符串可以使用正则表达式或者内置函数来处理的时候,选择内置函数。
str.isalpha(),str.isdigit(),str.startswith(('x', 'yz'))
(3)对字符进行格式化比直接串联读取要快,因此要使用
out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
而避免
out = "<html>" + head + prologue + query + tail + "</html>"
(4)使用列表解析和生成器表达式
列表解析 a=[w for w in list]【a=(w for w in list)会效率更高】
5)交换两个变量的值使用 a,b=b,a 而不是借助中间变量
6)使用局部变量,避免”global” 关键字
7)is not 比 !=快
8)在耗时较多的循环中,可以把函数的调用改为内联的方式
9)使用级联比较 “x < y < z” 而不是 “x < y and y < z”
参考连接link 定位程序性能瓶颈以及性能优化工具