Python 程式檢查兩個列表是否至少有一個共同元素
要檢查兩個列表是否至少有一個共同元素,我們將遍歷列表1和列表2,並檢查兩個列表中是否存在至少一個共同元素。列表是 Python 中最通用的資料型別,可以寫成方括號之間用逗號分隔的值(項)列表。關於列表的重要一點是,列表中的項不必是相同型別。
假設我們有以下輸入,即 2 個列表 -
[15, 45, 67, 30, 98] [10, 8, 45, 48, 30]
輸出應如下所示,即兩個列表至少有一個共同元素 -
Common Element Found
使用 for 迴圈檢查兩個列表是否至少有一個共同元素
我們使用了巢狀 for 迴圈來檢查使用者輸入的兩個列表是否至少有兩個元素。遍歷兩個列表,並使用 if 語句找到共同元素。input() 方法用於使用者輸入 -
示例
def commonFunc(A, B): c = "Common Element Not Found" # traverse in the 1st list for i in A: # traverse in the 2nd list for j in B: # if one common if i == j: c="Common Element Found" return c return c # Driver code A=list() B=list() n1=int(input("Enter the size of the first List =")) print("Enter the Element of the first List =") for i in range(int(n1)): k=int(input("")) A.append(k) n2=int(input("Enter the size of the second List =")) print("Enter the Element of the second List =") for i in range(int(n2)): k=int(input("")) B.append(k) print("Display Result =",commonFunc(A, B))
輸出
Enter the size of the first List =5 Enter the Element of the first List = 15 45 67 30 98 Enter the size of the second List =7 Enter the Element of the second List = 10 8 45 48 30 86 67 Display Result = Common Element Found Enter the size of the first List =5 Enter the Element of the first List = 10 20 30 40 50 Enter the size of the second List =5 Enter the Element of the second List= 23 39 45 67 89 Display Result = Common Element Not Found
使用 set_intersection() 檢查兩個列表是否至少有一個共同元素
我們使用了 set_intersection() 方法來檢查兩個列表是否至少有一個共同元素。首先,將列表轉換為集合,然後應用該方法查詢共同元素 -
示例
def commonFunc(list1, list2): p_set = set(p) q_set = set(q) if len(p_set.intersection(q_set)) > 0: return True return False # First List p = [4, 10, 15, 20, 25, 30] print("List1 = ",p) # Second List q = [12, 24, 25, 35, 45, 65] print("List2 = ",q) print("Are common elements in both the lists? ",commonFunc(p, q))
輸出
List1 = [4, 10, 15, 20, 25, 30] List2 = [12, 24, 25, 35, 45, 65] Are common elements in both the lists? True
使用集合檢查兩個列表是否至少有一個共同元素
在此示例中,我們使用了 set() 方法將列表轉換為集合,然後使用 & 運算子查詢共同元素。因此,我們在這裡沒有使用 set_intersection() 方法 -
示例
def commonFunc(list1, list2): p_set = set(p) q_set = set(q) if (p_set & q_set): return True else: return False # First List p = [5, 10, 15, 20, 25, 30] print("List1 = ",p) # Second List q = [12, 20, 30, 35, 40, 50] print("List2 = ",q) print("Are common elements in both the lists? ",commonFunc(p, q))
輸出
List1 = [5, 10, 15, 20, 25, 30] List2 = [12, 20, 30, 35, 40, 50] Are common elements in both the lists? True
上面我們看到返回了 True,因為兩個列表至少有一個共同元素。在此示例中,共同元素是 30。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP