删除另一个列表中的一个列表中的元素

rod*_*ocf 7 python list

我有list1list2.list2是一组必须从中删除的单词,list1例如:

list1=['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i', 'me', 'me']

list2=["i","me"]
Run Code Online (Sandbox Code Playgroud)

期望的输出:

list3=['paste', 'text', 'text', 'here', 'here', 'here', 'my']
Run Code Online (Sandbox Code Playgroud)

我尝试过使用'for'的不同版本但到目前为止没有结果.

任何想法,将不胜感激!

ale*_*cxe 17

使用列表理解:

>>> 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']
Run Code Online (Sandbox Code Playgroud)

注意:列表中的查找是O(n),考虑从中创建一个集合list2 - 集合中的查找O(1).

  • 始终使用列表理解.虽然对于Python新手,我觉得应该解释列表推导. (2认同)

Mar*_*ace 5

如何利用集算术?

diff = set(list1) - set(list2)
result = [o for o in list1 if o in diff]
Run Code Online (Sandbox Code Playgroud)

甚至更好(更有效):

set2 = set(list2)
result = [o for o in list1 if o not in set2]
Run Code Online (Sandbox Code Playgroud)