2016-12-06 147 views
0

嗨,我有以下2個列表,我想獲得第三個更新列表基本上是這樣的,如果從列表'錯誤'的任何字符串出現在列表'舊'它過濾掉包含它的整行字符串。即我想要更新的列表等同於「新」列表。搜索並從另一個字符串列表中刪除字符串

wrong = ['top up','national call'] 
old = ['Hi Whats with ','hola man top up','binga dingo','on a national call'] 
new = ['Hi Whats with', 'binga dingo'] 

回答

2

您可以使用filter

>>> list(filter(lambda x:not any(w in x for w in wrong), old)) 
['Hi Whats with ', 'binga dingo'] 

或者,list comprehension

>>> [i for i in old if not any(x in i for x in wrong)] 
['Hi Whats with ', 'binga dingo'] 

如果你不舒服任何這些,用一個簡單的像基於循環解決方案如下:

>>> result = [] 
>>> for i in old: 
...  for x in wrong: 
...   if x in i: 
...    break 
...  else: 
...   result.append(i) 
... 
>>> result 
['Hi Whats with ', 'binga dingo'] 
0
>>> wrong = ['top up','national call'] 
>>> old = ['Hi Whats with ','hola man top up','binga dingo','on a national call'] 
>>> [i for i in old if all(x not in i for x in wrong)] 
['Hi Whats with ', 'binga dingo'] 
>>> 
相關問題