I have two lists 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 it matches l1[0]
any l2[2]
, in this case there should be a [1, l1[0],l2[0]]
conclusion, otherwise there will be a conclusion [0, l1[0], l2[0]]
. The output should be one nested list (or a list of tuples) with the result for each element l1
. Both lists may have different sizes.
I tried to solve this using for-loop, for example:
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 gives the correct conclusion.
[[1, 1, 'c'], [1, 4, 'a'], [0, 7]]
However, I am looking for a more compact solution. Is it possible to solve this with a list of understanding of something similar that can reduce the number of lines involved?
I tried 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')]]