如何获取具有唯一属性的对象列表 [英] How to get list of objects with unique attribute
问题描述
我有一个list
.
此list
有许多对象.每个对象都有一个id
.现在,这些对象具有不同的类型.
I have a list
.
This list
has many objects. Each object has an id
. Now the objects are of different types.
objects = [Aobject, Bobject, Cobject]
其中
>>> Aobject != Bobject
True
>>> Aobject.id == Bobject.id
True
问题
我想要一个基于object.id
的唯一对象list
.
Problem
I want a list
of unique objects based on the object.id
.
类似这样的东西:
set(objects, key=operator.attrgetter('id'))
(这不起作用.但是我想要这样的东西)
(This does not work. But I want something like this)
推荐答案
seen = set()
# never use list as a variable name
[seen.add(obj.id) or obj for obj in mylist if obj.id not in seen]
之所以可行,是因为set.add
返回None
,因此列表推导中的表达式始终会产生obj
,但前提是尚未将obj.id
添加到seen
中.
This works because set.add
returns None
, so the expression in the list comprehension always yields obj
, but only if obj.id
has not already been added to seen
.
(如果obj is None
,则表达式只能求值为None
;在这种情况下,obj.id
会引发异常.如果mylist
包含None
值,则将测试更改为if obj and (obj.id not in seen)
)
(The expression could only evaluate to None
if obj is None
; in that case, obj.id
would raise an exception. In case mylist
contains None
values, change the test to if obj and (obj.id not in seen)
)
请注意,这将为您提供列表中具有给定ID的第一个对象. @Abhijit的回答将为您提供最后一个这样的对象.
Note that this will give you the first object in the list which has a given id. @Abhijit's answer will give you the last such object.
更新:
或者,ordereddict可能是一个不错的选择:
Alternatively, an ordereddict could be a good choice:
import collections
seen = collections.OrderedDict()
for obj in mylist:
# eliminate this check if you want the last item
if obj.id not in seen:
seen[obj.id] = obj
list(seen.values())
这篇关于如何获取具有唯一属性的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!