在Python列表中查找并replacestring值
我有这个清单:
words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really']
我想要的是用类似于<br />
一些奇妙值代替[br]
从而得到一个新的名单:
words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really']
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']
您可以使用,例如:
words = [word.replace('[br]','<br />') for word in words]
如果你想知道不同方法的性能,下面是一些时机:
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的最短部分。