2010-06-28 53 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的最短部分。