技巧大集合,熬夜总结53个Python使用技巧和攻击方法( 三 )

控制警告消息的输出
$ python -W all# 输出所有警告 , 等同于设置warnings.simplefilter('always')$ python -W ignore# 忽略所有警告 , 等同于设置warnings.simplefilter('ignore')$ python -W error# 将所有警告转换为异常 , 等同于设置warnings.simplefilter('error')4.2 代码中测试有时为了调试 , 我们想在代码中加一些代码 , 通常是一些 print 语句 , 可以写为:
# 在代码中的debug部分if __debug__:pass一旦调试结束 , 通过在命令行执行 -O 选项 , 会忽略这部分代码:
$ python -0 main.py4.3 代码风格检查使用 pylint 可以进行不少的代码风格和语法检查 , 能在运行之前发现一些错误
pylint main.py4.4 代码耗时耗时测试
$ python -m cProfile main.py测试某代码块耗时
# 代码块耗时定义from contextlib import contextmanagerfrom time import perf_counter@contextmanagerdef timeblock(label):tic = perf_counter()try:yieldfinally:toc = perf_counter()print('%s : %s' % (label, toc - tic))# 代码块耗时测试with timeblock('counting'):pass代码耗时优化的一些原则

  • 专注于优化产生性能瓶颈的地方 , 而不是全部代码 。
  • 避免使用全局变量 。局部变量的查找比全局变量更快 , 将全局变量的代码定义在函数中运行通常会快 15%-30% 。
  • 避免使用.访问属性 。使用 from module import name 会更快 , 将频繁访问的类的成员变量 self.member 放入到一个局部变量中 。
  • 尽量使用内置数据结构 。str, list, set, dict 等使用 C 实现 , 运行起来很快 。
  • 避免创建没有必要的中间变量 , 和 copy.deepcopy() 。
  • 字符串拼接 , 例如 a + ‘:’ + b + ‘:’ + c 会创造大量无用的中间变量 , ’:’,join([a, b, c]) 效率会高不少 。另外需要考虑字符串拼接是否必要 , 例如 print(’:’.join([a, b, c])) 效率比 print(a, b, c, sep=’:’) 低 。
5. Python 其他技巧5.1 argmin 和 argmaxitems = [2, 1, 3, 4]argmin = min(range(len(items)), key=items.__getitem__)argmax同理 。
5.2 转置二维列表A = [['a11', 'a12'], ['a21', 'a22'], ['a31', 'a32']]A_transpose = list(zip(*A))# list of tupleA_transpose = list(list(col) for col in zip(*A))# list of list5.3 一维列表展开为二维列表A = [1, 2, 3, 4, 5, 6]# Preferred.list(zip(*[iter(A)] * 2))



推荐阅读