Home  >  Q&A  >  body text

How to subtract two lists in Python?

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_leeringa_lee2685 days ago1799

reply all(5)I'll reply

  • 黄舟

    黄舟2017-06-12 09:24:36

    A = [item for item in A if item not in set(B)]

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-12 09:24:36

    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)

    reply
    0
  • 高洛峰

    高洛峰2017-06-12 09:24:36

    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()

    reply
    0
  • 三叔

    三叔2017-06-12 09:24:36

    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

    reply
    0
  • 黄舟

    黄舟2017-06-12 09:24:36

    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()

    reply
    0
  • Cancelreply