首頁  >  文章  >  後端開發  >  如何在Python中有效率地從一個清單中減去另一個清單?

如何在Python中有效率地從一個清單中減去另一個清單?

Patricia Arquette
Patricia Arquette原創
2024-10-23 13:50:03980瀏覽

How to Subtract One List from Another Efficiently in Python?

從一個列表中減去另一個列表:高效技術和自定義實現

從一個列表中減去另一個列表是程式設計中的常見操作。在 Python 中,直接使用 - 運算子執行此操作可能會受到限制。要有效地減去列表,請考慮以下方法:

列表理解

從一個列表(y) 中減去另一個列表(x),同時保留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) 直接在清單上工作,一可以建立自訂類別:

<code class="python">class MyList(list):
    ...
    def __sub__(self, other):
        ...</code>

重寫__sub__ 方法可以啟用自訂減法行為,提供所需的功能。

用法範例:

<code class="python">x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 3, 5, 7, 9]

# List Comprehension
result_comprehension = [item for item in x if item not in y]
print(result_comprehension)  # [0, 2, 4, 6, 8]

# Set Difference
result_set = list(set(x) - set(y))
print(result_set)  # [0, 2, 4, 6, 8]

# Custom Class
class MyList(list):
    ...
x_custom = MyList([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y_custom = MyList([1, 3, 5, 7, 9])
result_custom = x_custom - y_custom 
print(result_custom)  # [0, 2, 4, 6, 8]</code>

這些方法提供了在 Python 中減去清單的不同方法,取決於特定要求和所需的行為。

以上是如何在Python中有效率地從一個清單中減去另一個清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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