Home > Enterprise >  Searching for duplicate values in a multiple 2D arrays
Searching for duplicate values in a multiple 2D arrays

Time:03-20

I am figuring to get a method to search the duplicated parts in a 2D array in Python.

Taking the below array for example:

Array1 = [[1, 7], [2, 7], [3, 7], [4, 7], [5, 7], [6, 7], [7, 7]]

Array2 = [[5, 8], [5, 7], [5, 6], [5, 5], [5, 4]]

Array3 = [[1, 7], [2, 7], [3, 7], [4, 7], [5, 7], [6, 7], [7, 7]]

ArrayN = [......]

the result I would like to get is like this:

Array_result = [[5,7]]

Is there any method that can automatically search the duplicated areas and save the coordinates?

CodePudding user response:

Here is one way to do so, converting lists to set().

data = [
    [[1, 7], [2, 7], [3, 7], [4, 7], [5, 7], [6, 7], [7, 7]],
    [[5, 8], [5, 7], [5, 6], [5, 5], [5, 4]],
    [[1, 7], [2, 7], [3, 7], [4, 7], [5, 7], [6, 7], [7, 7]],
]

arr_result = set(tuple(x) for x in data[0])
for arr in data[1:]:
    arr_result.intersection_update(tuple(x) for x in arr)
print(arr_result)  # {(5, 7)}

As each list contains sub-lists, they must be converted into tuples, because lists are unhashable.

We convert the first list to a set(), then for each list in data, we intersect the set and the list using intersection_update().


Using list comprehension:

arr_result = set.intersection(*[{tuple(x) for x in arr} for arr in data])
print(arr_result)  # {(5, 7)}

CodePudding user response:

Cubix48 solution using list comprehension should be preferred, use the below just as reference for other problems.


Using collections:

from collections import Counter

array_list = [[str(x) for x in array] for array in [Array1, Array2, Array3]]
c = Counter()
for item in array_list:
    c.update(item)

repeated_items = [eval(item) for item in dict(c).keys() if c[item] == len(array_list)]
  • Related