Python 检查两个列表是否至少有一个共同元素

Python 检查两个列表是否至少有一个共同元素

为了检查两个列表是否至少有一个共同的元素,我们将循环遍历list1和list2,并在两个列表中至少有一个共同元素的情况下进行检查。列表是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()方法将列表转换为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。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程