Python 使用集合在三个列表中找到共同的元素

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]

使用交集操作符在三个列表中找到共同的元素

在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]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程