How to subtract two lists in Python?
ringa_lee
ringa_lee 2017-06-12 09:22:36
0
5
1892

There is an ordered date list A['2016-01-01','2016-01-02','2016-01-03',....'2017-06-01']
And an unordered list of dates that need to be excluded B['2016-03-02','2016-03-08',]
I hope to put A Remove all B elements contained in . Is there anything wrong with the following writing?

for x in B:
    A.remove(x)
ringa_lee
ringa_lee

ringa_lee

reply all(5)
黄舟
A = [item for item in A if item not in set(B)]
巴扎黑
a = ['2016-01-01','2016-01-02','2016-01-03','2017-06-01', '2016-03-08']
b = ['2016-03-02','2016-03-08',]
print set(a) - set(b)
小葫芦

It depends on your needs. There is nothing wrong with it and there is not a lot of data. I will provide you with a solution

from collections import OrderedDict

d_set = OrderedDict.fromkeys(A)

for x in B:
    del d_set[x]

A = d_set.keys()
三叔

This way of writing will report an error. If x is not in A, an error will be reported. This way of writing can first add an if to determine whether x is in A and then execute A.remove(x)

Try this simple way of writing:

#coding=utf-8
A = ['2016-01-01','2016-01-02','2016-01-03','2017-06-01','2017-06-01','2016-03-08','2016-03-08']
B = ['2016-03-02','2016-03-08']
C = []
for a in A:
    for b in B:
        if a == b:
            break
    else:
        C.append(a)
        
print C
黄舟

from collections import OrderedDict
A = ['2016-01-01','2016-01-02','2016-01-03','2017-06-01','2016-03-08']
B = ['2016-03-02','2016-03-08']
d_set = OrderedDict.fromkeys(A)
for x in B:

if x in A:
    del d_set[x]

A = d_set.keys()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template