搜索并从另一个字符串列表中删除字符串

2024-09-30 16:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有以下两个列表,我想得到第三个更新的列表,基本上这样,如果列表中的任何字符串'错误'出现在列表'旧'它过滤掉整个字符串行包含它。我希望更新后的列表与“新”列表相同

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']

Tags: 字符串列表top错误withcallhiold
2条回答
>>> 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']
>>> 

您可以使用filter

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

或者,a list comprehension

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

如果您对其中任何一个都不满意,请使用以下基于for循环的简单解决方案:

>>> result = []
>>> for i in old:
...     for x in wrong:
...         if x in i:
...             break
...     else: 
...         result.append(i)
... 
>>> result
['Hi Whats with ', 'binga dingo']

相关问题 更多 >