为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁花不似锦 2023-05-23 14:42:47
我有一个 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。否则什么都不做。另请参阅“最正确的方法”以正确执行此操作(投票答案)。
查看完整描述

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>


查看完整回答
反对 回复 2023-05-23
?
湖上湖

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


查看完整回答
反对 回复 2023-05-23
?
慕妹3146593

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')]


查看完整回答
反对 回复 2023-05-23
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

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)


查看完整回答
反对 回复 2023-05-23
  • 4 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信