」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在保留順序的同時有效地從 Python 清單中刪除重複的物件?

如何在保留順序的同時有效地從 Python 清單中刪除重複的物件?

發佈於2024-11-03
瀏覽:938

How Do I Efficiently Remove Duplicate Objects from a Python List While Preserving Order?

使用 Python 高效處理重複對象

在 Python 中,可能需要從列表中刪除重複對象,同時保持原始順序。當您有自訂物件清單並希望根據某些條件過濾重複項或檢查資料庫中的重複項時,就會出現此問題。

根據您的特定要求,您需要定義物件內的唯一性才能有效使用set(list_of_objects) 方法。這涉及透過實作 eqhash 方法使物件可哈希。

eq 方法定義物件相等性。例如,如果您的Book 物件具有author_name 和title 屬性,其中作者和標題的組合是唯一的,則eq 方法可能如下所示:

def __eq__(self, other):
    return self.author_name == other.author_name and self.title == other.title

同樣,hash方法產生物件的雜湊值。常見的方法是對關鍵屬性的元組進行雜湊處理:

def __hash__(self):
    return hash(('title', self.title, 'author_name', self.author_name))

有了這些方法,您現在可以從Book 物件清單中刪除重複項:

books = [Book('title1', 'author1'), Book('title2', 'author2'), Book('title1', 'author1')]
unique_books = list(set(books))

此外,要檢查資料庫中的重複項,可以使用以下方法:

import sqlalchemy

session = sqlalchemy.orm.sessionmaker()()
records = session.query(YourModel).all()
existing_titles = set([record.title for record in records])
unique_objects = [obj for obj in objects if obj.title not in existing_titles]
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3