I got two list of lists
l1 = [[1,2,3],[4,5,6],[7,8,9]]
l2 = [['a','b',4],['c','d',1],['e','f',12],['i','j',18]]
I would like to iterate over l1 and check if l1[0] matches with any l2[2], In this case the output should be [1, l1[0],l2[0]] otherwise output is [0, l1[0], l2[0]]. Output should be a single nested list(or list of tuples) with result for each element of l1. Both lists can have different sizes.
I tried solving this with for-loop like:
output = list()
for i in l1:
matched = 0
for j in l2:
if j[2] == i[0]:
output.append([1,i[0], j[0]])
matched = 1
if matched == 0:
output.append([0,i[0]])
This give correct output
[[1, 1, 'c'], [1, 4, 'a'], [0, 7]]
However I am looking for a more compact solution. Is it possible to solve this with list comprehension of something similar which can reduce number of lines involved?
I tried a nested list comprehension but couldn't make it work
out = [[(1,i[0],k[0]) if(k[2] == i[0]) else (0,i[0],k[0]) for k in l2] for i in l1]
print(out)
[[(0, 1, 'a'), (1, 1, 'c'), (0, 1, 'e'), (0, 1, 'i')], [(1, 4, 'a'), (0, 4, 'c'), (0, 4, 'e'), (0, 4, 'i')], [(0, 7, 'a'), (0, 7, 'c'), (0, 7, 'e'), (0, 7, 'i')]]
dictfor finding what you search for?dicthere[next(([1, x[0], y[0]] for y in l2 if x[0] == y[-1]), [0, x[0], l2[-1][0]]) for x in l1]