Difference Between Two Lists with Duplicates in Python

后端 未结 5 1200
灰色年华
灰色年华 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:39

    Counters are new in Python 2.7. For a general solution to substract a from b:

    def list_difference(b, a):
        c = list(b)
        for item in a:
           try:
               c.remove(item)
           except ValueError:
               pass            #or maybe you want to keep a values here
        return c
    

提交回复
热议问题