首頁  >  文章  >  後端開發  >  如何在Python中尋找多個清單的交集?

如何在Python中尋找多個清單的交集?

Patricia Arquette
Patricia Arquette原創
2024-10-21 22:04:03229瀏覽

How to Find the Intersection of Multiple Lists in Python?

Python:交叉多個清單

使用多個清單時,尋找它們的共同元素可能是一項有價值的操作。雖然 Python 提供了一個方便的函數來相交兩個清單 (set(a).intersection(b)),但是當處理兩個以上清單時,任務會變得稍微複雜一些。

讓我們考慮一個場景,其中我們有一個包含多個清單的清單d 的清單(在您的範例中,d = [[1,2,3,4], [2,3, 4], [3,4,5,6,7]])。要找到 d 中所有清單的交集,我們可以利用 Python 的集合運算和內建函數。

一種方法是重複使用 set.intersection() 方法。然而,該方法一次只能對兩個集合進行操作,因此我們需要迭代地應用它。我們可以這樣做:

<code class="python">intersection = set(d[0])
for lst in d[1:]:
    intersection = intersection.intersection(set(lst))

print(intersection)  # Outputs: {3, 4}</code>

另一個簡潔高效的解決方案利用Python 的* 運算子和map() 函數:

<code class="python">intersection = set.intersection(*map(set, d))

print(intersection)  # Outputs: {3, 4}</code>

在此解決方案中,我們使用map( ) 函數將d 中的每個列表轉換為集合。然後 * 運算子將這個集合序列解壓縮到 set.intersection() 的參數中,使我們能夠同時找到所有集合的交集。

這兩種方法都可以有效地找到儲存在其中的多個清單的交集清單的清單。透過利用Python的集合運算,我們可以輕鬆識別任意數量的清單中的公共元素。

以上是如何在Python中尋找多個清單的交集?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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