使用集合查找三个列表中的公共元素的 Python 程序

programmingpythonserver side programming

在本文中,我们将学习如何在三个列表中查找公共元素。列表是 Python 中最通用的数据类型,可以写为方括号之间的逗号分隔值(项目)列表。列表的重要之处在于列表中的项目不必是同一类型。但是,Set 是 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() 的集合在三个列表中查找公共元素

Python 中使用 Intersection() 方法在三个列表中查找公共元素 -

示例

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]

相关文章