删除一个列表中存在于另一个列表中的元素 [英] remove elements in one list present in another list
本文介绍了删除一个列表中存在于另一个列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有list1
和list2
. list2
是一组必须从list1
中删除的单词,例如:
I have list1
and list2
. list2
is a group of words that have to be removed from list1
, for example:
list1=['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i', 'me', 'me']
list2=["i","me"]
所需的输出:
list3=['paste', 'text', 'text', 'here', 'here', 'here', 'my']
我尝试使用'for'的不同版本,但到目前为止没有结果.
I have tried different versions using 'for' but no results so far.
任何想法将不胜感激!
推荐答案
使用列表理解:
>>> list1 = ['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i', 'me', 'me']
>>> list2 = ["i","me"]
>>> list3 = [item for item in list1 if item not in list2]
>>> list3
['paste', 'text', 'text', 'here', 'here', 'here', 'my']
注意:列表中的查找为O(n)
,请考虑改用list2
中的集合 -集合中的查找为O(1)
.
NOTE: Lookups in lists are O(n)
, consider making a set from list2
instead - lookups in sets are O(1)
.
这篇关于删除一个列表中存在于另一个列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文