使用集合查找三个列表中共同元素的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]
广告