迭代查找/替换Python中的元组列表

3 python iteration django tuples list

我有一个元组列表,每个元组包含一个我想要应用于字符串的查找/替换值.最有效的方法是什么?我将迭代地应用它,因此性能是我最关心的问题.

更具体地说,processThis()的内部会是什么样子?

x = 'find1, find2, find3'
y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')]

def processThis(str,lst):
     # Do something here
     return something

>>> processThis(x,y)
'replace1, replace2, replace3'
Run Code Online (Sandbox Code Playgroud)

谢谢,全部!

mha*_*wke 6

您可以考虑使用re.sub:

import re
REPLACEMENTS = dict([('find1', 'replace1'),
                     ('find2', 'replace2'),
                     ('find3', 'replace3')])

def replacer(m):
    return REPLACEMENTS[m.group(0)]

x = 'find1, find2, find3'
r = re.compile('|'.join(REPLACEMENTS.keys()))
print r.sub(replacer, x)
Run Code Online (Sandbox Code Playgroud)

  • @mhawke:re.sub逐步浏览文本中的每个位置,并测试"find"是否匹配该位置 - 没有自动机.时间是O((文本的大小)*("发现"的数量)*("查找"的平均大小)).str.replace()的多种用途:相同.但是:str.replace使用Boyer-Moore变体快速跳过文本但是遍历文本多次,可能会破坏内存缓存,并且会因为每次必须替换"find"时创建一个新的替换字符串而切断内存.re.sub在没有跳过的情况下遍历文本一次,并且只创建一次repl字符串.重新获胜; 做基准. (3认同)