在Python程序中找到两个列表的交集?
交叉操作意味着,我们必须从List1和List2中获取所有公共元素,并将所有元素存储在另一个第三列表中。
List1::[1,2,3] List2::[2,3,6] List3::[2,3]
算法
Step 1: input lists. Step 2: first traverse all the elements in the first list and check with the elements in the second list. Step 3: if the elements are matched then store in third list.
范例程式码
#Intersection of two lists
def intertwolist(A, B):
C = [i for i in A if i in B]
return C
# Driver Code
A=list()
B=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element of first list::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
print("Enter the Element of second list::")
for i in range(int(n)):
k=int(input(""))
B.append(k)
print("THE FINAL LIST IS ::>",intertwolist(A, B))输出结果
Enter the size of the List ::5 Enter the Element of first list:: 12 23 45 67 11 Enter the Element of second list:: 23 45 88 11 22 THE FINAL LIST IS ::> [23, 45, 11]
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短