使用dict或set查找元素
合理使用生成器(generator)和yield
a = (i for i in range(100000)) #快
b = [i for i in range(100000)]
优化包含多个判断表达式的顺序
# 对于and,应该把满足条件少的放在前面,对于or,把满足条件多的放在前面。
使用join合并迭代器中的字符串
s = ''
a = ['s', 'rewr', 'eww']
for i in a:
s += i
s = ''.join(a) #快
选择合适的格式化字符方式(其实三种都差不多)
s1, s2 = 'ax', 'bx'
'abc%s%s' % (s1, s2)
'abc{0}{1}'.format(s1, s2)
'abc' + s1 + s2
不借助中间变量交换两个变量的值
a,b=1,2
c=a;a=b;b=c;
a,b=b,a #快
使用if not 比 if True 快
使用if is
a = range(10000)
[i for i in a if i == True]
[i for i in a if i is True] #快
使用级联比较x < y < z
while 1 比 while True 更快
使用而不是pow**
c = pow(2,20)
c = 2**20 #快
还有一些优化的地方,可以参考这里