使用集合查詢三個列表中共同元素的Python程式


在本文中,我們將學習如何查詢三個列表中的共同元素。列表是Python中最通用的資料型別,可以寫成方括號之間用逗號分隔的值(項)的列表。列表的重要一點是,列表中的項不必是相同型別。但是,集合是Python中的一個集合,它是無序的、不可更改的和無索引的。

假設我們有以下輸入:

a = [5, 10, 15, 20, 25]
b = [2, 5, 6, 7, 10, 15, 18, 20]
c = [10, 20, 30, 40, 50, 60]

以下應該是顯示共同元素的輸出:

[10, 20]

使用intersection()方法使用集合查詢三個列表中的共同元素

intersection()方法用於在Python中查詢三個列表中的共同元素:

示例

def IntersectionFunc(myArr1, myArr2, myArr3): s1 = set(myArr1) s2 = set(myArr2) s3 = set(myArr3) # Intersection set1 = s1.intersection(s2) output_set = set1.intersection(s3) # Output set set to list endList = list(output_set) print(endList) # Driver Code if __name__ == '__main__' : # Elements of 3 arrays myArr1 = [5, 10, 15, 20, 25] myArr2 = [2, 5, 6, 7, 10, 15, 18, 20] myArr3 = [10, 20, 30, 40, 50, 60] # Calling Function IntersectionFunc(myArr1, myArr2, myArr3)

輸出

[10, 20]

使用set()方法查詢三個列表中的共同元素

要查詢三個列表中的共同元素,我們可以使用set()方法:

示例

# Elements of 3 arrays myArr1 = [5, 10, 15, 20, 25] myArr2 = [2, 5, 6, 7, 10, 15, 18, 20] myArr3 = [10, 20, 30, 40, 50, 60] print("First = ",myArr1) print("Second = ",myArr2) print("Third = ",myArr3) # Finding common elements using set output_set = set(myArr1) & set(myArr2) & set(myArr3); # Converting the output into a list final_list = list(output_set) print("Common elements = ",final_list)

輸出

First =  [5, 10, 15, 20, 25]
Second =  [2, 5, 6, 7, 10, 15, 18, 20]
Third =  [10, 20, 30, 40, 50, 60]
Common elements =  [10, 20]

透過使用者輸入使用集合查詢三個列表中的共同元素

我們也可以透過使用者輸入來查詢三個列表中的共同元素:

示例

def common_ele(my_A, my_B, my_C):
	my_s1 = set(my_A)
	my_s2 = set(my_B)
	my_s3 = set(my_C)
	my_set1 = my_s1.intersection(my_s2)
	output_set = my_set1.intersection(my_s3)
	output_list = list(output_set)
	print(output_list)
if __name__ == '__main__' :
# First List
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
	p=int(input("Size="))
	A.append(int(p))
	print (A)
	# Second List
	B=list()
n1=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n1)):
	p=int(input("Size="))
	B.append(int(p))
	print (B)
	# Third Array
	C=list()
n2=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n2)):
	p=int(input("Size="))
	C.append(int(p))
	print (C)
	# Calling Function
	common_ele(A, B, C)

輸出

Enter the size of the List 3
Enter the number
Size= 2
[2]
Size= 1
[2, 1]
Size= 2
[2, 1, 2]
Enter the size of the List 3
Enter the number
Size= 2
[2]
Size= 1
[2, 1]
Size= 4
[2, 1, 4]
Enter the size of the List 4
Enter the number
Size= 3
[3]
[]
Size= 2
[3, 2]
[2]
Size= 1
[3, 2, 1]
[1, 2]
Size= 3
[3, 2, 1, 3]
[1, 2]

更新於:2022年8月12日

1K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告