Skip to main content
 首页 » 编程设计

python之删除与另一个列表中的任何条目匹配的列表条目

2025年05月04日11artech

我有一个诅咒词列表,我想与其他列表进行匹配以删除匹配项。我通常在个人基础上使用 list.remove('entry') ,但是针对另一个列表遍历条目列表 - 然后删除它们让我感到难过。有什么想法吗?

请您参考如下方法:

使用 filter :

>>> words = ['there', 'was', 'a', 'ffff', 'time', 'ssss'] 
>>> curses = set(['ffff', 'ssss']) 
>>> filter(lambda x: x not in curses, words) 
['there', 'was', 'a', 'time'] 
>>>  

也可以通过列表理解来完成:

>>> [x for x in words if x not in curses]