亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超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)


查看完整回答
反對 回復 2023-05-23
  • 4 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號