在 Python 中檢查一個列表是否是另一個列表的子集


Python 提供了多種方法來檢查一個列表是否為另一個列表的子集,例如'all()'函式,以及使用'issubset()'函式來有效地執行此檢查。以下列出了三種用於在 Python 中檢查一個列表是否為另一個列表的子集的主要方法。

  • all() 函式:檢查可迭代物件中的所有元素是否都為真。

  • issubet() 方法:在 Python 集合中用於收集唯一元素。

  • intersection() 方法:查詢兩個集合之間的公共元素。

使用 'all()' 函式

在 Python 中,all()如果可迭代物件中的所有元素都為真,則返回'True',否則返回False。我們可以使用此方法結合生成器表示式來檢查較小列表中的每個元素是否都存在於較大的列表中。

示例

在下面的示例程式碼中,'element in Alist for element in Asub_list'指的是與 'all()' 函式一起使用的生成器表示式,它根據 'all()' 函式的結果,針對 'Asub_list' 中的每個元素生成 True 或 False,我們根據 'all()' 函式的結果列印 'Asub_list' 是否為 'Alist' 的子集。

#  Define the main list and the sublist
Alist = ['Mon', 'Tue', 5, 'Sat', 9]
Asub_list = ['Tue', 5, 9]

print("Given list ",Alist)
print("Given sublist",Asub_list)

#  Check if Asub_list is a subset of Alist using all()
if all(element in Alist for element in Asub_list):
    print("Sublist is part of the bigger list")
else:
    print("Sublist is not part of the bigger list")

#  Test with another sublist
Asub_list = ['Wed', 5, 9]
if all(element in Alist for element in Asub_list):
    print("Sublist is part of the bigger list")
else:
    print("Sublist is not part of the bigger list")

輸出

Given list  ['Mon', 'Tue', 5, 'Sat', 9]
Given sublist ['Tue', 5, 9]
Sublist is part of the bigger list
Sublist is not part of the bigger list

使用 'issubet()' 方法

'issubet()'方法是 Python 集合資料結構提供的內建函式,它檢查一個集合的所有元素是否都存在於另一個集合中。我們必須將列表轉換為集合才能實現此方法,並更有效地檢查子集。

示例

在下面的程式碼中,使用 'set()' 建構函式將 'Asub_list''Alist' 都轉換為集合。方法 set(Asub_list).issubset(set(Alist))檢查集合 'Asub_list' 中的每個元素是否存在於 'Alist' 集合中。如果所有元素都存在,則返回 'True',否則列印 'False'

Alist = [1, 2, 3, 4, 4]
Asub_list = [4, 4]

# Using issubset()
print(set(Asub_list).issubset(set(Alist)))

輸出

True

使用 'intersection()' 方法

'intersection()' 方法返回一個包含兩個集合中共有元素的集合。透過比較交集結果並確定子列表是否為主列表的子集,將子列表轉換為集合。

示例

在下面的示例程式碼中,使用 'set(Alist)' 將 'Alist' 轉換為集合,並且 'set(Alist).intersection(Asub_list)' 將返回 'Alist''Asub_list' 中共有元素的集合。

# Define the main list and the sublist
Alist = ['Mon', 'Tue', 5, 'Sat', 9]
Asub_list = ['Tue', 5, 9]


# Convert lists to sets and use intersection()
if set(Alist).intersection(Asub_list) == set(Asub_list):
    print("Sublist is part of the bigger list")
else:
    print("Sublist is not part of the bigger list")

# Test with another sublist
Asub_list = ['Wed', 5, 9]
if set(Alist).intersection(Asub_list) == set(Asub_list):
    print("Sublist is part of the bigger list")
else:
    print("Sublist is not part of the bigger list")

輸出

Sublist is part of the bigger list
Sublist is not part of the bigger list

更新於: 2024年10月14日

4K+ 閱讀量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.