Python 中計算列表差異的方法有哪些?

Barbara Streisand
發布: 2024-10-23 11:53:01
原創
493 人瀏覽過

What are the Methods to Compute List Differences in Python?

如何計算清單差異

要確定兩個清單 x 和 y 之間的差異,Python 中有多種方法可用。

使用列表推導式

要保留x 中元素的順序,可以使用列表推導式:

<code class="python">[item for item in x if item not in y]</code>
登入後複製

此表達式建立一個功能新的列表,僅包括x 中不存在於y 中的元素。

使用集合差異

如果排序不重要,可以使用集合差異:

<code class="python">list(set(x) - set(y))</code>
登入後複製

此方法將x 和y 轉換為集合,計算差異,然後將結果轉換回列表。

重寫類別方法

要啟用中綴減法語法(例如,x - y),您可以重寫繼承自list 的類別中的 sub 方法:

<code class="python">class MyList(list):
    def __init__(self, *args):
        super(MyList, self).__init__(args)

    def __sub__(self, other):
        return self.__class__(*[item for item in self if item not in other])

x = MyList(1, 2, 3, 4)
y = MyList(2, 5, 2)
z = x - y  # Infix subtraction syntax</code>
登入後複製

在此場景中, z將只包含x 中不在y 中的元素。

以上是Python 中計算列表差異的方法有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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