Ad

Check If A String Inside A List Is Present In Another Nested List And Return It's Index In Nested List

- 1 answer

So i have two lists a normal list and a nested list say,

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]

I would like to check if any of the string in list1 is present in list2 and if so, return the indices of the string (which is in both the lists) in list2. Sample code which demonstrates the required output is shown below:

out = [(ind,ind2) for ind,i in enumerate(list2) 
    for ind2,y in enumerate(i) if 'john' in y]
print out

it returns : [(0, 0), (1, 1), (2, 1)]

the above code does output the indices but it is limited to the string that we manually input. Is it possible to do as i have explained above? any help would be appreciated.(fairly new to nested lists). Thanks!

Ad

Answer

You can simply loop over list1:

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]

res = {}
for w in list1: # if list1 contains duplicates use set(list1) instead
    # create an empty list for the name of list1 and extend it by all finds or
    # extend it by None
    res.setdefault(w,[]).extend( [(ind,ind2) for 
              ind,i in enumerate(list2) for ind2,y in enumerate(i) if w in y] or [None] )

# print all results by name
for k in res:
    print k, res[k]

# print all dict
print res

Output:

amal [None]
joel [None]
john [(0, 0), (1, 1), (2, 1)]
george [None]

{'amal': [None], 'joel': [None], 'john': [(0, 0), (1, 1), (2, 1)], 'george': [None]}

I am using a dict here, so you do not loose which one is where in the lists.

Ad
source: stackoverflow.com
Ad