查找并替换列表中的字符串值

我有个清单:

words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really']

我想要的是用一些类似于 <br />的奇妙的值来代替 [br],从而得到一个新的列表:

words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really']
528806 次浏览

你可以使用,例如:

words = [word.replace('[br]','<br />') for word in words]
words = [w.replace('[br]', '<br />') for w in words]

这些被称为 清单理解

除了列表内涵,你可以试试 地图

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

如果你想知道不同方法的性能,这里有一些时机:

In [1]: words = [str(i) for i in range(10000)]


In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop


In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop


In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop


In [5]: import re


In [6]: r = re.compile('1')


In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop

正如你所看到的,对于这些简单的模式,可接受的列表内涵是最快的,但是看看下面:

In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop


In [9]: r = re.compile('(1|324|567)')


In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop

这表明,对于更复杂的替换,预编译的 reg-exp (如 9-10)可以(快得多)。这实际上取决于您的问题和 reg-exp 中最短的部分。

一个 for 循环的例子(我更喜欢列表理解)。

a, b = '[br]', '<br />'
for i, v in enumerate(words):
if a in v:
words[i] = v.replace(a, b)
print(words)
# ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

如果性能很重要,那么包含 if-else子句可以提高性能(对于100万个字符串的列表,性能提高约5% ,这一点不容忽视)。

replaced = [w.replace('[br]','<br />') if '[br]' in w else w for w in words]

通过 operator.methodcaller()调用 replace(大约增加20%)可以改进 map()的实现,但是仍然慢于列表内涵(如 Python 3.9)。

from operator import methodcaller
list(map(methodcaller('replace', '[br]', '<br />'), words))

如果就地修改字符串就足够了,那么循环实现可能是最快的。

for i, w in enumerate(words):
if '[br]' in w:
words[i] = w.replace('[br]', '<br />')