Get difference between two lists

前端 未结 27 2833
傲寒
傲寒 2020-11-21 11:36

I have two lists in Python, like these:

temp1 = [\'One\', \'Two\', \'Three\', \'Four\']
temp2 = [\'One\', \'Two\']

I need to create a third

相关标签:
27条回答
  • 2020-11-21 11:44

    If you run into TypeError: unhashable type: 'list' you need to turn lists or sets into tuples, e.g.

    set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))
    

    See also How to compare a list of lists/sets in python?

    0 讨论(0)
  • 2020-11-21 11:45
    In [5]: list(set(temp1) - set(temp2))
    Out[5]: ['Four', 'Three']
    

    Beware that

    In [5]: set([1, 2]) - set([2, 3])
    Out[5]: set([1]) 
    

    where you might expect/want it to equal set([1, 3]). If you do want set([1, 3]) as your answer, you'll need to use set([1, 2]).symmetric_difference(set([2, 3])).

    0 讨论(0)
  • 2020-11-21 11:49

    i'll toss in since none of the present solutions yield a tuple:

    temp3 = tuple(set(temp1) - set(temp2))
    

    alternatively:

    #edited using @Mark Byers idea. If you accept this one as answer, just accept his instead.
    temp3 = tuple(x for x in temp1 if x not in set(temp2))
    

    Like the other non-tuple yielding answers in this direction, it preserves order

    0 讨论(0)
  • 2020-11-21 11:49

    Here are a few simple, order-preserving ways of diffing two lists of strings.

    Code

    An unusual approach using pathlib:

    import pathlib
    
    
    temp1 = ["One", "Two", "Three", "Four"]
    temp2 = ["One", "Two"]
    
    p = pathlib.Path(*temp1)
    r = p.relative_to(*temp2)
    list(r.parts)
    # ['Three', 'Four']
    

    This assumes both lists contain strings with equivalent beginnings. See the docs for more details. Note, it is not particularly fast compared to set operations.


    A straight-forward implementation using itertools.zip_longest:

    import itertools as it
    
    
    [x for x, y in it.zip_longest(temp1, temp2) if x != y]
    # ['Three', 'Four']
    
    0 讨论(0)
  • 2020-11-21 11:50

    Try this:

    temp3 = set(temp1) - set(temp2)
    
    0 讨论(0)
  • 2020-11-21 11:50
    (list(set(a)-set(b))+list(set(b)-set(a)))
    
    0 讨论(0)
提交回复
热议问题