我得到了这个清单:
words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really']
我想要的是将[br]
替换为类似于<br />
的奇妙值,从而获得一个新列表:
words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really']
答案 0 :(得分:204)
words = [w.replace('[br]', '<br />') for w in words]
答案 1 :(得分:29)
除列表理解外,您还可以尝试地图
>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']
答案 2 :(得分:28)
您可以使用,例如:
words = [word.replace('[br]','<br />') for word in words]
答案 3 :(得分:14)
如果你想知道不同方法的表现,这里有一些时间:
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的最短部分。
答案 4 :(得分:0)
带有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']