2010-06-28 55 views
90

我得到这个列表替换字符串值:查找和Python列表

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

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

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

回答

143

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

称为List Comprehensions

+3

在这个列表理解方法和地图方法(由@Anthony Kong发布)之间进行比较,这个列表方法大约快两倍。还允许在同一个呼叫中插入多个替换,例如替换('D','THY')替换('D','THY')替换名称在ncp.resname()]'中 – 2015-04-20 18:50:11

24

可以使用,例如:

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

与上述接受的答案相同。 – macetw 2017-01-04 18:20:05

26

除了列表解析,你可以尝试地图

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

如果你想知道的不同方法的表现,这里有一些计时:

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 

正如你可以看到的这样简单的模式接受的列表理解是最快的,但看看t他以下几点:

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的最短部分。