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'} |
从
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'] |