2015-05-04 23 views
1

我想從列表中的項目中刪除特定的字符,使用另一個列表作爲參考。目前,我有:如何從列表中的項目中刪除字符,使用另一個列表作爲參考

forbiddenList = ["a", "i"] 
tempList = ["this", "is", "a", "test"] 
sentenceList = [s.replace(items.forbiddenList, '') for s in tempList] 
print(sentenceList) 

,我希望這將打印:

["ths", "s", "test"] 
當然

,禁止的名單是相當小的,我可以逐個更換,但我想知道如何做到這一點當我有一個廣泛的「禁止」項目列表時,「正確」。

+0

我喜歡做這些事情有一個正則表達式 - 正則表達式甚至有哪些是有用的類 - (如爭取刪除所有不可打印的字符) –

+0

反正這是一個dup - http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python –

回答

3

您可以使用嵌套列表理解。

>>> [''.join(j for j in i if j not in forbiddenList) for i in tempList] 
['ths', 's', '', 'test'] 

好像你還想要刪除的元素,如果他們成爲空(如,所有的人物都是在forbiddenList)?如果是這樣,你可以用在整個事件中,甚至另一個列表比較(在可讀性爲代價)

>>> [s for s in [''.join(j for j in i if j not in forbiddenList) for i in tempList] if s] 
['ths', 's', 'test'] 
+0

這是整齊,避免「作弊」與正則表達式,其中純粹的列表理解,在Python中完全支持,工作正常。 – gustafbstrom

1
>>> templist = ['this', 'is', 'a', 'test'] 
>>> forbiddenlist = ['a', 'i'] 
>>> trans = str.maketrans('', '', ''.join(forbiddenlist)) 
>>> [w for w in (w.translate(trans) for w in templist) if w] 
['ths', 's', 'test'] 

這是使用str.translatestr.maketrans一個Python 3溶液。它應該很快。

你也可以做到這一點在Python 2,但str.translate界面略有不同:

>>> templist = ['this', 'is', 'a', 'test'] 
>>> forbiddenlist = ['a', 'i'] 
>>> [w for w in (w.translate(None, ''.join(forbiddenlist)) 
...   for w in templist) if w] 
['ths', 's', 'test'] 
相關問題