4 回答
TA贡献1831条经验 获得超9个赞
最干净的方法是,如果您能够SomeObject自己定义类,则通过定义SomeObject唯一性并指定允许唯一性比较的__eq__,__ne__和方法。刚刚添加,以便我们可以用值打印它而不是打印例如__hash____str__<__main__.SomeObject object at 0x10b2dedf0>
class SomeObject:
def __init__(self, id, name):
self.id = id
self.name = name
def __eq__(self, other):
return isinstance(other, self.__class__) and self.id == other.id
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash(self.id)
def __str__(self):
return "<SomeObject id={} name={}>".format(self.id, self.name)
然后你可以申请set,从而过滤掉重复的对象,并将其转换回列表:
my_list = [
SomeObject(id="hello", name="world"),
SomeObject(id="hello", name="world"),
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>
TA贡献2003条经验 获得超2个赞
循环遍历 my_list 中的每个元素,检查 expected_list 中的所有元素:如果其中任何元素匹配 id,则不要将其添加到列表中。
def delete_duplicates(total_list):
expected_list = []
in_expected_list = False
for i in total_list:
for j in expected_list:
if j.id == i.id:
in_expected_list = True
if not in_expected_list:
expected_list.append(i)
in_expected_list = False
return expected_list
TA贡献1820条经验 获得超9个赞
将 ID 添加到集合中,然后删除不唯一的列表成员:
def some_object(id="bar", name="baz"):
return id, name
my_list = [
some_object(id="hello", name="world"),
some_object(id="hello", name="world"),
some_object(id="foo", name="bar"),
]
print(my_list)
ids = set()
for obj in my_list:
if (id := obj[0]) in ids:
del my_list[my_list.index(obj)]
ids.add(obj[0])
print(my_list)
返回:
[('hello', 'world'), ('hello', 'world'), ('foo', 'bar')]
[('hello', 'world'), ('foo', 'bar')]
TA贡献1906条经验 获得超3个赞
itertools.groupby您可以像这样使用:
class SomeObject:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
my_list = [
SomeObject(id="hello", name="world"),
SomeObject(id="foo", name="bar"),
SomeObject(id="hello", name="world")
]
from itertools import groupby
sort_function = lambda obj: obj.id
my_list = [list(item)[0]
for key, item in groupby(sorted(my_list, key=sort_function), key=sort_function)]
print(my_list)
添加回答
举报