How to get those elements which are at the same position in two 2D matrix in Python using a filter?

Viewed 38

I am trying to get the elements as a list if any of them in the same position in two 2D matrices.

Let's consider matrix A and matrix B

A = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
B = [[0, 2, 5],[6, 2, 4],[7, 8, 1]]

The resultant list should be

C = [2, 7, 8]

I have tried using a filter but it is not working.

def find(A):
    for i in range(3):
        for j in range(3):
            if A[i][j] == B[i][j]:
                return A[i][j]
            else:
                return False

A = [[1, 2, 3],[4, 5, 6], [7, 8, 9]]
B = [[0, 2, 5],[6, 2, 4], [7, 8, 1]]

C = filter(find, A)

for element in C:
    print(element)

Note: Please use a filter to achieve the target.

4 Answers

Solution using filter:

def find(L):
            A, B = L
            if A == B:
                return True
            else:
                return False

A = [[1, 2, 3],[4, 5, 6], [7, 8, 9]]
B = [[0, 2, 5],[6, 2, 4], [7, 8, 1]]

# flatten lists
A = [item for row in A for item in row]
B = [item for row in B for item in row]

C = filter(find, zip(A,B))

# filter returns a tuple for each row but we only want the single element
C = [item[0] for item in C]

print(list(C))

Gives us

[2, 7, 8]

Try this,

def func(t):
    return True if t[0] == t[1] else False

A = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
B = [[0, 2, 5],[6, 2, 4],[7, 8, 1]]

C = [item1 for lst1, lst2 in zip(A, B) for item1, item2 in filter(func, zip(lst1, lst2))]
>>> C
[2, 7, 8]

Basic Answer

First we loop over A and B, i and z now holds the inner lists.

Then we loop over those inner lists using g and q, if they are equal, we append them to the empty list.

to_fill = []
for i,z in zip(A,B):
    for g,q in zip(i,z):
        if g==q:
            to_fill.append(g)

Adapt it as you please.

The most efficient way of achieving what you want is by using numpy:

import numpy as np
A = np.asarray(A)
B = np.asarray(B)
C = A[A==B]
Related