📌  相关文章
📜  Python|打印两个列表的所有公共元素

📅  最后修改于: 2022-05-13 01:55:00.422000             🧑  作者: Mango

Python|打印两个列表的所有公共元素

给定两个列表,打印两个列表的所有公共元素。

例子:

Input : list1 = [1, 2, 3, 4, 5] 
        list2 = [5, 6, 7, 8, 9]
Output : {5}
Explanation: The common elements of 
both the lists are 3 and 4 

Input : list1 = [1, 2, 3, 4, 5] 
        list2 = [6, 7, 8, 9]
Output : No common elements 
Explanation: They do not have any 
elements in common in between them

方法一:使用Set的&属性

将列表转换为集合,然后打印set1&set2 。 set1&set2 返回公共元素集合,其中 set1 是 list1,set2 是 list2。
下面是上述方法的 Python3 实现:

Python3
# Python program to find the common elements
# in two lists
def common_member(a, b):
    a_set = set(a)
    b_set = set(b)
 
    if (a_set & b_set):
        print(a_set & b_set)
    else:
        print("No common elements")
          
  
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
common_member(a, b)
  
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
common_member(a, b)


Python3
# Python program to find common elements in
# both sets using intersection function in
# sets
 
 
# function
def common_member(a, b):   
    a_set = set(a)
    b_set = set(b)
     
    # check length
    if len(a_set.intersection(b_set)) > 0:
        return(a_set.intersection(b_set)) 
    else:
        return("no common elements")
     
  
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b))
  
a =[1, 2, 3, 4, 5]
b =[6, 7, 8, 9]
print(common_member(a, b))


输出:

{5}
No common elements

方法二:使用Set的intersection属性

将列表转换为通过转换设置。使用交集函数来检查两个集合是否有任何共同的元素。如果它们有许多共同的元素,则打印两组的交集。
下面是上述方法的 Python3 实现:

Python3

# Python program to find common elements in
# both sets using intersection function in
# sets
 
 
# function
def common_member(a, b):   
    a_set = set(a)
    b_set = set(b)
     
    # check length
    if len(a_set.intersection(b_set)) > 0:
        return(a_set.intersection(b_set)) 
    else:
        return("no common elements")
     
  
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b))
  
a =[1, 2, 3, 4, 5]
b =[6, 7, 8, 9]
print(common_member(a, b))

输出:

{5}
No common elements

方法3:使用for循环

def common_member(a, b):
    result = [i for i in a if i in b]
    return result

a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]

print("The common elements in the two lists are: ")
print(common_member(a, b))