comparing two list of lists with unequal size of each element list

1.6k Views Asked by At

I have two lists of lists that I am working on: L=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]] A=[[1,2],[4,5]] I want to compare L with A such that the following outputs should be appended in a separate list K=[3,6] This function should check the first row of list A i.e. [1,2] with the first two elements of the row of list L i.e. [1,2] and if they are equal, the third element of the row in List L will be stored in a separate list K. Can someone give a working code or at least point me in the correct direction?

So far I've come up with this :

k=[]
for i in range(len(L)):
    if A[i][0]==l[i][0] and A[i][1]==L[i][1]:
        k.append(L[i][2])

The error that I am getting is "IndexError: list index out of range"

Thanks in advance! :)

1

There are 1 best solutions below

2
On BEST ANSWER

This should achieve what you are looking for (its bit sloppy to use len() and you might encounter an error if your lists vary in length)

L=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
A=[[7,8],[4,5]]
K=[]
for x in range(len(A)):
    for y in range(len(L)):
        if A[x] == L[y][:2]:
            K.append(L[y][2])
print K
out: [9, 6]