Laura Smith
Laura Smith

Reputation: 313

Check if a number exists in another list in python

I have two lists which contain the following type of information.

List #1:
Request = ["1/1/1.34", "1/2/1.3.5", "1/3/1.2.3", ...same format elements]
List #2:
Reply = ["1/1/0", "1/3/1", "1/2/0", ...same format elements]

From the "Reply" list, I want to be able to compare the second item in the "#/#/#", in this case it will be 1,3,2, and so on with all the items in the Reply list and check if there is a match with the second item in "Request list". If there is a match, then I want to be able to return a new list which would contain the information of the third index in the request string appended with the third index of the matching string in the reply.

The result would be like the following. 
Result = ["1.34.0", "1.3.5.0", "1.2.3.1"] 

Note that the 0 was appended to the 1.34, the 1 was appended to the 1.3.4 and the 0 was appended to the 1.2.3 from the corresponding indexes in the "Reply" list as the second index existed in the "Reply" list. The 'Reply" list could have the item anywhere placed in the list.

I am unable to figure out a simple way to compare both the list one by one element for the second index. I am really confused and I would be grateful if anyone could give help me out here.

Thanks

Upvotes: 1

Views: 302

Answers (2)

rrcal
rrcal

Reputation: 3752

You can also build it with list comprehension and string comparison:

res = [f"{i.split('/')[-1]}.{j.split('/')[-1]}" \
                      for i in Request for j in Reply \
                      if i.split('/')[1] == j.split('/')[1] ]

res
Out[1]:
['1.34.0', '1.3.5.0', '1.2.3.1']

Upvotes: 2

Marcus Weinberger
Marcus Weinberger

Reputation: 379

You could try getting only the items you're interested in and then comparing. Something like this:

iRequest = {}
for x in Request:
    iRequest[x.split('/')[1]] = x

That would give you a dictionary looking like this:

{'1':'1/1/1.34', '2':'1/2/1.35', ...and so on}

After doing the same but with the Reply list, you could go through every item in the new iReply (or whatever you choose to call it) dictionary and check if it is in iRequest. Eg:

similar = []
for x in iReply:
    if x in iRequest:
        similar.append(iReply[x])

Upvotes: 1

Related Questions