【发布时间】:2016-03-21 03:57:42
【问题描述】:
我试图在 Python 3.4 中使用 text.translate() 从给定字符串中删除不需要的字符。
最少的代码是:
import sys
s = 'abcde12345@#@$#%$'
mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$')
print(s.translate(mapper))
它按预期工作。然而,相同的程序在 Python 3.4 和 Python 3.5 中执行时会产生很大的差异。
计算时间的代码是
python3 -m timeit -s "import sys;s = 'abcde12345@#@$#%$'*1000 ; mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$'); " "s.translate(mapper)"
Python 3.4 程序需要 1.3ms,而 Python 3.5 中的相同程序只需要 26.4μs。
与 Python 3.4 相比,Python 3.5 的哪些改进使其更快?
【问题讨论】:
-
当我们谈论性能时,像这样生成映射器不是更好吗:
dict.fromkeys(ord(c) for c in '@#$')? -
@ThomasK 我发现这有很大的不同。是的,你的方式更好。
-
你的意思是快 50 倍?
-
@assylias 我做了 1300 - 26.4,然后除以 1300。我得到了将近 95%,所以我写了 :) 它实际上快了 50 倍以上……但是我的计算错了吗?我数学有点弱。我很快就会学数学。 :)
-
你应该这样做:26 / 1300 = 2% 所以更快的版本只需要慢版本的 2% => 它快 50 倍。
标签: python string python-3.x python-internals python-3.5