I have written a program where a user inputs numbers in two different lists then the program outputs the numbers that are similar between the lists.
example bellow:
List 1: 7 2 0 4
List 2: 4 2 0 0
output: [4 , 2, 0 ]
Currently my code achieves that but for some reason if there is more then one duplicate number it only prints the first duplicate number instead of all instances of duplicate numbers.
List 1: 7 2 0 4
List 2: 4 2 0 0
Output: [4]
see bellow my code.
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]
Any help would be appreciated.
CodePudding user response:
The problem is that b
is a map object which is consumed by the first iteration over its members. map
does not create a list, but a generator-like entity that can only be iterated once.
If you call list
on the map object, you will get a list that behaves as anticipated in the comprehension that makes c
.
Try this:
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]
However, we don't even need map
, since we can call int
in the comprehension itself. This makes much more Pythonic code, so unless you're working in a functional environment where iterators and generators are preferred:
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]
Your comprehension will give every member of b
that is in a
, which from your comments looks unintended. If you want only one instance, you can call set
on b
inside the comprehension.
CodePudding user response:
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])
Looking for all common element in both list using list comprehension, duplicates included
o/p---[0, 2, 4, 2, 0]
print([a for a in set(List1) if a in List2])
Remove the duplicate elements {set(List1)} then search for common element
o/p---[0,2,4]
print(set(List1).intersection(set(List2)))
Use SET intersection method to find common elements
o/p---[0,2,4]