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

Barbara Streisand
發布: 2024-10-27 00:22:30
原創
338 人瀏覽過

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

使用 Python 高效處理重複對象

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

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

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

<code class="python">def __eq__(self, other):
    return self.author_name == other.author_name and self.title == other.title</code>
登入後複製

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

<code class="python">def __hash__(self):
    return hash(('title', self.title, 'author_name', self.author_name))</code>
登入後複製

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

<code class="python">books = [Book('title1', 'author1'), Book('title2', 'author2'), Book('title1', 'author1')]
unique_books = list(set(books))</code>
登入後複製

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

<code class="python">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]</code>
登入後複製

以上是如何在保留順序的同時有效地從 Python 清單中刪除重複的物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!