首頁  >  文章  >  後端開發  >  Python 中計算列表差異的方法有哪些?

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

Barbara Streisand
Barbara Streisand原創
2024-10-23 11:53:01493瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn