Python 程式用於列印兩個列表的所有公共元素。


給定兩個列表,列印兩個列表的所有公共元素。

示例 −

Input : L1 = [5, 6, 7, 8, 9] 
        L2 = [5, 13, 34, 22, 90]
Output : {5}

說明

兩個列表的公共元素是 5。

演算法

Step1 : create two user input lists.
Step2 : Convert the lists to sets and then print set1&set2.
Step3 : set1 and set2 returns the common elements set, where set1 is the list1 and set2 is the list2.

示例程式碼

# Python program to find the common elements  
# in two lists 
def commonelemnets(a, b): 
   seta = set(a) 
   setb = set(b) 
   if (seta & setb): 
      print("Common Element ::>",seta & setb) 
   else: 
      print("No common elements")  
              
A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k) 
B=list()
n=int(input("Enter the size of the Second List ::"))
print("Enter the Element of Second List ::")
for i in range(int(n)):
   k=int(input(""))
   B.append(k) 
commonelemnets(A,B)

輸出

Enter the size of the First List :: 4
Enter the Element of First List ::
4
5
6
7
Enter the size of the Second List :: 4
Enter the Element of Second List ::
1
2
3
4
Common Element ::> {4}
Enter the size of the First List :: 4
Enter the Element of First List ::
1
2
3
4
Enter the size of the Second List :: 4
Enter the Element of Second List ::
5
6
7
8
No common elements

更新於: 30-Jul-2019

939 次瀏覽

啟動您的 職業生涯

透過完成課程取得認證

開始
廣告