Search code examples
pythonlist-comprehensionnested-loops

Nested loop with conditional list comprehension


I have 2 lists

l1 = [['a',1],['b',2],['c',3]] l2 = [['b',2,10],['c',3,8]]

I want the below code to be replicated using list comprehension in python:

for i in range(len(l1)):
    cnt = 0
    for j in range(len(l2)):
        if (l1[i][0]==l2[j][0]) & (l1[i][1]==l2[j][1]):
            cnt = 1
    if cnt==1:
        isintb.append(1)
    else:
        isintb.append(0)

expected output: [0,1,1]

can you guys help??

I tried as below:

[[1 if (l1[i][0]==l2[j][0]) & (l1[i][1]==l2[j][1]) else 0 for j in range(len(l2))] for i in range(len(l1))]

got output as below: [[0, 0], [1, 0], [0, 1]]


Solution

  • Since the inner for actually check if there is any match you can use any in the list comprehensions and cast the bool to int

    isintb = [int(any((l1[i][0] == l2[j][0]) & (l1[i][1] == l2[j][1]) for j in range(len(l2)))) for i in range(len(l1))]
    # [0, 1, 1]