pythonlistcomplement

how to find complement in two lists


There are two phones, phoneA and phoneB, how to how to find complement in phoneB but not in phoneA, one ex;

phoneA =  ["long lasting battery”, ”clear display”, ”great camera”, ”storage space”], [“clear display”, ”long lasting battery”, ”great camera”, ”warp-speed word processing”]

phoneB =  ["long lasting battery”, ”clear display”, ”great camera”, ”storage space”], [“clear display”, ”long lasting battery”, ”great camera”, ”warp-speed word processing”, “great sound”]

I write code like this by python:

d = [x for x in phoneB if x not in phoneA]
print(d)

but the code is wrong, anyone has better idea?


Solution

  • You need to add the 2 lists together, then check them:

    d = [x for x in phoneB[0]+phoneB[1] if x not in phoneA[0]+phoneA[1]]
    
    >>> d
    ['great sound']
    

    Or if you have multiple sublists, this will also work:

    # This joins all the elements in sublists into one large list
    d = [x for x in [j for i in phoneB for j in i]
         if x not in [j for i in phoneA for j in i]]