Compare items in one nested list with another nested list

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 l1and 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')]]
+4
source
2

, . , dict l2 (, , )

, , 2 3 , , ( int(if a in l2d), 0 1). :

l1 = [[1,2,3],[4,5,6],[7,8,9]]
l2 = [['a','b',4],['c','d',1],['e','f',12],['i','j',18]]

l2d = {v[2]:v[0] for v in l2}  # not using v[1]

result = [[1,a,l2d[a]] if a in l2d else [0,a] for a,_,_ in l1]  # using only first element of each l1 triplet...

:

[[1, 1, 'c'], [1, 4, 'a'], [0, 7]]

( , )

+3

, .

d = { c: a for [a,b,c] in l2 }

:

[[int(a in d), a] + ([d[a]] if a in d else [])
 for a,b,c in l1]

[[1, 1, 'c'], [1, 4, 'a'], [0, 7]]
+1

Source: https://habr.com/ru/post/1691195/


All Articles