首页 > 解决方案 > 从另一个列表中删除一组不同值的所有实例?

问题描述

list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
list2 = ['a', 3, 'b']

是否可以将 list2 中的值从 list1 中完全删除并输出:

[1, c, 5]

标签: python-3.x

解决方案


With the given lists,

>>> list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
>>> list2 = ['a', 3, 'b']

Use list comprehension

>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 5]

When we change list2, the output is as expected:

>>> list2 = ['a', 5, 'b']
>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 3, 3, 3]

推荐阅读