接受两个包含数字的列表并从两个列表输出 duplicate/similar 数字的程序

Program that takes two lists containing numbers and outputs the duplicate/similar numbers from both lists

我写了一个程序,用户在两个不同的列表中输入数字,然后程序输出列表之间相似的数字。

示例如下:

List 1: 7 2 0 4
List 2: 4 2 0 0 
output: [4 , 2, 0 ]

目前我的代码实现了这一点,但出于某种原因,如果有一个以上的重复数字,它只打印第一个重复数字,而不是所有重复数字的实例。

List 1: 7 2 0 4
List 2: 4 2 0 0
Output: [4]

看下面我的代码。

a = map(int, input('List 1: ').strip().split())  # e.g. "7 2 0 4"
b = map(int, input('List 2: ').strip().split())  # e.g. "4 2 0 0"
c = [el for el in b if el in a]
print('Output:',c) # e.g [4,2,0]

如有任何帮助,我们将不胜感激。

问题是 b 是一个映射对象,它在其成员的第一次迭代中被消耗。 map创建的不是列表,而是generator-like实体,只能迭代一次。

如果您在地图对象上调用 list,您将获得一个列表,该列表的行为与理解中的预期一致,使得 c.

试试这个:

a = list(map(int, input('List 1: ').strip().split()))  # e.g. "7 2 0 4")
b = list(map(int, input('List 2: ').strip().split()))  # e.g. "4 2 0 0")
c = [el for el in b if el in a]
print('Output:',c) # e.g [4,2,0]

然而,我们甚至不需要 map,因为我们可以在理解本身中调用 int。这会生成更多 Pythonic 代码,因此除非您在首选迭代器和生成器的函数式环境中工作:

a = input('List 1: ').strip().split()  # e.g. "7 2 0 4")
b = input('List 2: ').strip().split()  # e.g. "4 2 0 0")
c = [int(el) for el in b if el in a]

根据您的理解,b 中的每个成员都在 a 中,从您的评论来看,这似乎不是故意的。如果你只想要一个实例,你可以在推导中的 b 上调用 set

List1 = list(map(int, input('List 1: ').strip().split())) #0,1,2,4,2,0
List2 = list(map(int, input('List 2: ').strip().split())) #0,4,2,5,0,3  

print([a for a in List1 if a in List2])  

使用列表理解在两个列表中查找所有公共元素,包括重复项
o/p---[0, 2, 4, 2, 0]

print([a for a in set(List1) if a in List2])  

删除重复元素 {set(List1)} 然后搜索共同元素
o/p---[0,2,4]

print(set(List1).intersection(set(List2)))  

使用SET求交集方法查找公共元素
o/p---[0,2,4]