关于python:如何从列表中删除项目与其他列表列表进行比较

How to remove items from lista comparing with another list listb

本问题已经有最佳答案,请猛点这里访问。

我有两个列表lista和listb,试图通过删除listb中存在的所有元素来更新lista,我该怎么做?

1
2
3
4
5
Lista = ['1535408', '1527610', '1532634']
Listb = ['1527610', '1532634']

EXPECTED OUTPUT:-
 Lista = ['1535408']


使用列表理解

1
2
3
4
>>> Lista = ['1535408', '1527610', '1532634']
>>> Listb = ['1527610', '1532634']
>>> Lista = [item for item in Lista if item not in Listb]
['1535408']

如果不想保留重复的元素,则:

1
2
>>> set(Lista).difference(Listb)
{'1535408'}

Listb的元素中创建一个集合(用于o(1)查找时间)。使用列表理解和重新分配来进行筛选。

1
2
3
4
5
6
>>> Lista = ['1535408', '1527610', '1532634']
>>> Listb = ['1527610', '1532634']
>>> b_items = set(Listb)
>>> Lista = [item for item in Lista if item not in b_items]
>>> Lista
['1535408']