簡體   English   中英

用於在python中查找替換列表的itertools或functools

[英]itertools or functools for find-replace list in python

我有一組有時無效的字符串,我想用特別好的字符串替換。 我一直在玩functools和itertools,並想嘗試應用這些問題,但我有點卡住了。 這就是我所擁有的:

s1 = 'how to sing songs'
s2 = 'This is junk'
s3 = "This is gold"
s4 = 'HTML'
s5 = 'html'
s6 = 'i'
mylist = [s1,s2,s3,s4,s5,s6]

replacements = [('html','HTML'),('how to sing songs','singing'),('This is junk', ''),('i','')]

我想要一個函數算法,對於mylist中的每個字符串,對於替換中的每個替換,string.replace(replacement [0],replacement [1])。

想到什么樣的東西就像......

map(lambda x,y: x.replace(y[0],y[1]),mylist,replacements)
map(partial(lambda x,y: x.replace(y[0],y[1]),mylist),replacements)

但是第一個想要額外的參數,第二個說列表對象沒有屬性替換。 有沒有一個靈活的功能方式來解決這個問題?

>>> [reduce(lambda x, y: x.replace(y[0], y[1]), replacements, s) for s in mylist]
['singing', '', 'This is gold', 'HTML', 'HTML']

使用map()而不是list comprehension的等效代碼:

map(partial(reduce, lambda x, y: x.replace(y[0], y[1]), replacements), mylist)

聽起來你想要一些非常快的東西。 在這種情況下,你應該真正使用字典,因為查找非常快。

一個工作的例子:

mylist = ['how to sing songs', 'This is junk', "This is gold", 'HTML', 'html', 'i']
replacements = {'html':'HTML', 'how to sing songs':'singing', 'This is junk':'', 'i':''}

print [replacements.get(word, word) for word in mylist]  
# ['singing', '', 'This is gold', 'HTML', 'HTML', ''] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM