python3注意事项
目录
优化循环
循环之外能做的事不要放在循环内.
优化包含多个判断表达式的顺序
对于and,应该把满足条件少的放在前面,对于or,把满足条件多的放在前面。
使用join合并迭代器中的字符串
不借助中间变量交换两个变量的值
a, b = b, a
使用if is
使用 if is True 比 if == True 将近快一倍。
使用级联比较x < y < z
x < y < z效率略高,而且可读性更好。
while 1 比 while True 更快
使用**而不是pow
**就是快10倍以上!
使用计数器对象计数
>>> from collections import Counter
>>> c = Counter("hello world")
>>> c
Counter({"l": 3, "o": 2, " ": 1, "e": 1, "d": 1, "h": 1, "r": 1, "w": 1})
>>> c.most_common(2)
[("l", 3), ("o", 2)]
在Python 2中使用Python 3式的输出/除法
from __future__ import print_function
from __future__ import division