Python程序使用集合在三个列表中查找通用元素
给定三个用户输入列表,我们的任务是从这三个列表中找出共同的元素。在这里,我们正在应用交集方法。
示例
Input A=[2, 3, 4, 5, 6] B=[2, 3, 7, 6, 90] C=[2, 3, 45, 34] Common elements=[2, 3]
算法
Step1: input the elements of three lists. Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.
范例程式码
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]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短