Home > Enterprise >  How to extract common elements from two 2D array using Python?
How to extract common elements from two 2D array using Python?

Time:06-28

I'm working on to extract common elements/values from a two 2D arrays using python script. I know we can extract common elements in two lists.

Example:

Here, a and b are two 2D arrays:

a = [[1,2],[3,4],[5,6]...]
b = [[7,8],[1,2],[87,65],[3,4]...]

and output should be an another 2D array:

c = [[1,2],[3,4]]

How to achieve this?

CodePudding user response:

You can traverse a list and use the in operator to check if the selected element is on b:

a = [[1,2],[3,4],[5,6]]
b = [[7,8],[1,2],[87,65],[3,4]]

l = [i for i in a if i in b]
print(l)

Output:

[[1, 2], [3, 4]]

CodePudding user response:

Convert the lists of lists to sets of tuples, then find their intersection:

def tuple_set(seq):
    return {tuple(item) for item in seq}

print(tuple_set(a) & tuple_set(b))

If needed, convert the result back to a list of lists:

print([list(item) for item in tuple_set(a) & tuple_set(b)])
  • Related