2

Index only duplicates in a multidimensional array.

Example

a = [[279, 629, 590], [382, 825, 279], [629, 569, 113], [382, 785, 296]]

3D array with duplicates, I want to return the row and column of duplicates.

results = [[[279], [[0, 0], [1, 3]], [[629], [[0, 1], [2, 0]], [[382], [[1, 0], [3, 0]]]

I am looking to return only the duplicate elements along with the row and columns.

5
  • 4
    That's an interesting problem; how have you tried to solve it? Commented Mar 4, 2016 at 19:39
  • Is using Numpy an option? It would make things easier. (And technically, there are no arrays in the Python core language, let alone multi-dimensional arrays. There are lists of lists, but that's something different, and the difference matters in some cases.) Commented Mar 4, 2016 at 19:41
  • I really didn't know where to start with solving this problem. I like to provide attempts to this problem. Commented Mar 4, 2016 at 19:45
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. on topic and how to ask apply here. Commented Mar 4, 2016 at 19:45
  • I think I can use numpy to get the column and row length and then loop through the multidimensional array, adding found duplicates to a dictionary. Commented Mar 4, 2016 at 19:46

1 Answer 1

1

One possible solution for this problem is to get a dict (I used a defaultdict because it is nicer if one doesn't need to initiate empty lists by hand) where the key is the value and the value is a list of the coordinates for this value:

a = [[279, 629, 590], [382, 825, 279], [629, 569, 113], [382, 785, 296]]
from collections import defaultdict
elements = defaultdict(list)
for row_index in range(len(a)):
    for col_index in range(len(a[row_index])):
        elements[a[row_index][col_index]].append([row_index, col_index])

The next step would be to create a list of the value and the coordinates like you specified:

multiples = [[[i], elements[i]] for i in elements if len(elements[i]) > 1]

Which would be:

[[[629], [(0, 1), (2, 0)]],
 [[279], [(0, 0), (1, 2)]],
 [[382], [(1, 0), (3, 0)]]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.