Get difference between two lists

前端 未结 27 2799
傲寒
傲寒 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:55

    Here's a Counter answer for the simplest case.

    This is shorter than the one above that does two-way diffs because it only does exactly what the question asks: generate a list of what's in the first list but not the second.

    from collections import Counter
    
    lst1 = ['One', 'Two', 'Three', 'Four']
    lst2 = ['One', 'Two']
    
    c1 = Counter(lst1)
    c2 = Counter(lst2)
    diff = list((c1 - c2).elements())
    

    Alternatively, depending on your readability preferences, it makes for a decent one-liner:

    diff = list((Counter(lst1) - Counter(lst2)).elements())
    

    Output:

    ['Three', 'Four']
    

    Note that you can remove the list(...) call if you are just iterating over it.

    Because this solution uses counters, it handles quantities properly vs the many set-based answers. For example on this input:

    lst1 = ['One', 'Two', 'Two', 'Two', 'Three', 'Three', 'Four']
    lst2 = ['One', 'Two']
    

    The output is:

    ['Two', 'Two', 'Three', 'Three', 'Four']
    

提交回复
热议问题