Python:过滤具有唯一ID值的列表中的对象

我有一个 Python 中的对象列表,例如:

my_list = [
    SomeObject(id="hello", name="world"),
    SomeObject(id="hello", name="world"),
    SomeObject(id="foo", name="bar"),
]

现在我想要一个新列表,它只包含具有唯一值的对象id,所以预期的列表将是:

expected_list = [
    SomeObject(id="hello", name="world"),
    SomeObject(id="foo", name="bar"),
]

Python 中是否有一种方法可以执行这样的列表过滤?


更新:

我最后要做的是,创建两个列表,unique_id_list = []unique_object_list = []。for-loop:如果object.id不在unique_id_list,则将 id 追加到unique_id_list, item in 中unique_object_list。否则什么都不做。另请参阅“最正确的方法”以正确执行此操作(投票答案)。


繁花不似锦
浏览 145回答 4
4回答

天涯尽头无女友

最干净的方法是,如果您能够SomeObject自己定义类,则通过定义SomeObject唯一性并指定允许唯一性比较的__eq__,__ne__和方法。刚刚添加,以便我们可以用值打印它而不是打印例如__hash____str__<__main__.SomeObject object at 0x10b2dedf0>class SomeObject:&nbsp; &nbsp; def __init__(self, id, name):&nbsp; &nbsp; &nbsp; &nbsp; self.id = id&nbsp; &nbsp; &nbsp; &nbsp; self.name = name&nbsp; &nbsp; def __eq__(self, other):&nbsp; &nbsp; &nbsp; &nbsp; return isinstance(other, self.__class__) and self.id == other.id&nbsp; &nbsp; def __ne__(self, other):&nbsp; &nbsp; &nbsp; &nbsp; return not self == other&nbsp; &nbsp; def __hash__(self):&nbsp; &nbsp; &nbsp; &nbsp; return hash(self.id)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; def __str__(self):&nbsp; &nbsp; &nbsp; &nbsp; return "<SomeObject id={} name={}>".format(self.id, self.name)然后你可以申请set,从而过滤掉重复的对象,并将其转换回列表:my_list = [&nbsp; &nbsp; SomeObject(id="hello", name="world"),&nbsp; &nbsp; SomeObject(id="hello", name="world"),&nbsp; &nbsp; SomeObject(id="foo", name="bar"),]filtered = list(set(my_list))# print all objects in the list:[print(o) for o in filtered]将打印出过滤列表中的项目:<SomeObject id=hello name=world><SomeObject id=foo name=bar>

湖上湖

循环遍历 my_list 中的每个元素,检查 expected_list 中的所有元素:如果其中任何元素匹配 id,则不要将其添加到列表中。def delete_duplicates(total_list):&nbsp; &nbsp; expected_list = []&nbsp; &nbsp; in_expected_list = False&nbsp; &nbsp; for i in total_list:&nbsp; &nbsp; &nbsp; &nbsp; for j in expected_list:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if j.id == i.id:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; in_expected_list = True&nbsp; &nbsp; &nbsp; &nbsp; if not in_expected_list:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expected_list.append(i)&nbsp; &nbsp; &nbsp; &nbsp; in_expected_list = False&nbsp; &nbsp; return expected_list

慕妹3146593

将 ID 添加到集合中,然后删除不唯一的列表成员:def some_object(id="bar", name="baz"):&nbsp; &nbsp; return id, namemy_list = [&nbsp; &nbsp; some_object(id="hello", name="world"),&nbsp; &nbsp; some_object(id="hello", name="world"),&nbsp; &nbsp; some_object(id="foo", name="bar"),]print(my_list)ids = set()for obj in my_list:&nbsp; &nbsp; if (id := obj[0]) in ids:&nbsp; &nbsp; &nbsp; &nbsp; del my_list[my_list.index(obj)]&nbsp; &nbsp; ids.add(obj[0])print(my_list)返回:[('hello', 'world'), ('hello', 'world'), ('foo', 'bar')][('hello', 'world'), ('foo', 'bar')]

一只名叫tom的猫

itertools.groupby您可以像这样使用:class SomeObject:&nbsp; &nbsp; def __init__(self, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; self.__dict__.update(kwargs)my_list = [&nbsp; &nbsp; SomeObject(id="hello", name="world"),&nbsp; &nbsp; SomeObject(id="foo", name="bar"),&nbsp; &nbsp; SomeObject(id="hello", name="world")]from itertools import groupbysort_function = lambda obj: obj.idmy_list = [list(item)[0]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for key, item in groupby(sorted(my_list, key=sort_function), key=sort_function)]print(my_list)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python