使用系统库,效率非常低:
foo = "foo bar car haz can bar foo"
repl = {('foo', 'bar'), ('car', 'bar'), ('foo', 'haz')}
for rep in repl:
foo = foo.replace(rep)
替换批次replace
应该在O(| foo | + | repl |)而不是O(| foo |×| repl |)中解决此问题,如上述方法。
您能想到实现这种更有效解决方案的简洁方法吗?
答案 0 :(得分:1)
使用正则表达式
import re
foo = "foo bar car haz can bar foo"
re.sub(r"(foo|car)", "bar", foo)
> 'bar bar bar haz can bar bar'
实际上在这种情况下速度较慢:
import timeit
timeit.timeit('re.sub(r"(foo|car)", "bar", "foo bar car haz can bar foo")', 'import re', number=10000)
> 0.051492929458618164
def test():
foo = "foo bar car haz can bar foo"
repl = [('foo', 'bar'), ('car', 'bar'), ('foo', 'haz')]
for rep in repl:
foo = foo.replace(*rep)
timeit.timeit("test()", setup="from __main__ import test", number=10000)
> 0.026629924774169922