Reputation: 1
I am trying to run the code
list = ["ABCD", "LMN" , "STU" , "PQRS" ]
dict = ["ABCD" , "LMN" , "PQRS" ]
for i in list:
for j in dict:
if (i == j):
print(i,j)
else:
print(i,j,"No match")
Expected output is,
ABCD ABCD
LMN LMN
STU No match
PQRS PQRS
But as it is comparing i with each value of j , Its giving me output as,
('ABCD', 'ABCD')
('ABCD', 'LMN', 'No match')
('ABCD', 'PQRS', 'No match')
('LMN', 'ABCD', 'No match')
('LMN', 'LMN')
('LMN', 'PQRS', 'No match')
('STU', 'ABCD', 'No match')
('STU', 'LMN', 'No match')
('STU', 'PQRS', 'No match')
('PQRS', 'ABCD', 'No match')
('PQRS', 'LMN', 'No match')
('PQRS', 'PQRS')
i tried with break and continue statements still not getting expected result Can anybody help me with this?
Upvotes: 0
Views: 35
Reputation: 125
you can do with filter like this
results = list(filter(lambda x: x in dict,list))
Upvotes: 0
Reputation: 561
Seems like you are getting tuples instead of strings you hoped. Remove the parenthesis after print
then you will get what you want.
print(i,j)
=>print i,j
You got twice the expected output because your for loops check every element in the lists twice.
An easier way other than mentioned in the other answer is to use set
module.
A =set(["1","2",.....])
B =set(["2","3",.....])
set.intersection(A,B)
BTW, avoid using list
as your variable name. That is a preserved word.
Upvotes: 1
Reputation: 7826
You have a nested for loop - as such, you will compare each i in list with every single j in dict.
You could try the following instead:
for i in list:
if i in dict: # checks if the string exists in dict.
print(i, i)
else:
print(i, "No match")
Upvotes: 2