Python - 檢查兩個列表是否有共同元素
在使用 Python 列表操作資料時,我們經常會遇到需要知道兩個列表是否完全不同或者它們是否有任何共同元素的情況。這可以透過比較兩個列表中的元素來實現,以下描述了幾種方法。
使用 in
在 for 迴圈中,我們使用 in 語句來檢查某個元素是否在一個列表中。我們將擴充套件此邏輯,透過從第一個列表中選擇一個元素並檢查它是否存在於第二個列表中來比較列表的元素。因此,我們將使用巢狀 for 迴圈來進行此檢查。
示例
#Declaring lists
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
list3=[12,3,12,15,14,15,17]
list4=[12,42,41,12,41,12]
# In[23]:
#Defining function to check for common elements in two lists
def commonelems(x,y):
common=0
for value in x:
if value in y:
common=1
if(not common):
return ("The lists have no common elements")
else:
return ("The lists have common elements")
# In[24]:
#Checking two lists for common elements
print("Comparing list1 and list2:")
print(commonelems(list1,list2))
print("\n")
print("Comparing list1 and list3:")
print(commonelems(list1,list3))
print("\n")
print("Comparing list3 and list4:")
print(commonelems(list3,list4))執行以上程式碼將得到以下結果
輸出
Comparing list1 and list2: The lists have common elements Comparing list1 and list3: The lists have no common elements Comparing list3 and list4: The lists have common elements
使用集合
另一種查詢兩個列表是否具有共同元素的方法是使用集合。集合是無序的唯一元素集合。因此,我們將列表轉換為集合,然後透過組合給定的集合建立一個新集合。如果它們有一些共同元素,則新集合將不為空。
示例
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
# Defining function two check common elements in two lists by converting to sets
def commonelem_set(z, x):
one = set(z)
two = set(x)
if (one & two):
return ("There are common elements in both lists:", one & two)
else:
return ("There are no common elements")
# Checking common elements in two lists for
z = commonelem_set(list1, list2)
print(z)
def commonelem_any(a, b):
out = any(check in a for check in b)
# Checking condition
if out:
return ("The lists have common elements.")
else:
return ("The lists do not have common elements.")
print(commonelem_any(list1, list2))執行以上程式碼將得到以下結果
輸出
('There are common elements in both lists:', {'d', 'e'})
The lists have common elements.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP