Difference Between Two Lists with Duplicates in Python

后端 未结 5 1227
灰色年华
灰色年华 2020-11-30 06:09

I have two lists that contain many of the same items, including duplicate items. I want to check which items in the first list are not in the second list. For example, I mig

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 06:32

    You didn't specify if the order matters. If it does not, you can do this in >= Python 2.7:

    l1 = ['a', 'b', 'c', 'b', 'c']
    l2 = ['a', 'b', 'c', 'b']
    
    from collections import Counter
    
    c1 = Counter(l1)
    c2 = Counter(l2)
    
    diff = c1-c2
    print list(diff.elements())
    

提交回复
热议问题