0

Given the data below, how would I print elements of a list within a list that were present within another list within a different list?

Example;

a = [['P101','John','Jones','100'], ['P102','Steve','Woodhouse','500'], ['P103','Ben','Jacobs','60']]
b = [['P101','John','Jones','250'], ['P102','Steve','Woodhouse','500']

I would like to print 'John Jones' & 'Steve Woodhouse' even though 'John Jones''s list is slightly different (his ID 'P101' still appears in both lists). I would also like to print 'Steve Woodhouse' but not 'Ben Jacobs', because he is not present in both lists.

2 Answers 2

1

One of the approaches can be. This checks if the same ID is present in both the lists. (Not a efficient one)

>>> for i in a:
...     if i[0] in (j[0] for j in b):
...         print("{} {}".format(i[1],i[2]))
... 
John Jones
Steve Woodhouse
Sign up to request clarification or add additional context in comments.

2 Comments

This is awesome, and works perfectly, however as you mention it is not efficient (I will be working with rather large data sets), is this the best approach to take?
@B-B. Yep this is a slow way! But it will work quite well if you store (j[0] for j in b) in a variable and leave the print to some file as screen printing is a slow process :)
1

You could create dictionaries instead and then intersect the keys using the viewkeys function like so:

a = [['P101','John','Jones','100'], ['P102','Steve','Woodhouse','500'], ['P103','Ben','Jacobs','60']]
b = [['P101','John','Jones','250'], ['P102','Steve','Woodhouse','500']]

ad = { p[0]: "{} {}".format(p[1],p[2]) for p in a}
bd = { p[0]: "{} {}".format(p[1],p[2]) for p in b}
common_id = ad.viewkeys() & bd.viewkeys()

for id in common_id:
    print ad[id]

Live example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.