List of objects with a unique attribute

前端 未结 2 1057
挽巷
挽巷 2021-01-17 09:43

I have a list of objects that each have a specific attribute. That attribute is not unique, and I would like to end up with a list of the objects that is a subset of the en

相关标签:
2条回答
  • 2021-01-17 10:18

    You could create a dict whose key is the object's thing and values are the objects themselves.

    d = {}
    for obj in object_list:
        d[obj.thing] = obj
    desired_list = d.values()
    
    0 讨论(0)
  • 2021-01-17 10:26

    You can use a list comprehension and set:

    objects = (object1,object2,object3,object4)
    seen = set()
    unique = [obj for obj in objects if obj.thing not in seen and not seen.add(obj.thing)]
    

    The above code is equivalent to:

    seen = set()
    unique = []
    for obj in objects:
        if obj.thing not in seen:
            unique.append(obj)
            seen.add(obj.thing)
    
    0 讨论(0)
提交回复
热议问题