1

I have a 2D array like this:

map = [[0, 1, 1], [0, 2, 1], [0, 2, 2]]

I would like to get array of indexes based on values. For example map[0][0] == 0 so I would like the pair (0, 0) to be on index 0 in the result array. The result array should look like this:

result[0] = [(0, 0), (1, 0), (2, 0)]
result[1] = [(0, 1), (0, 2), (1, 2)]
result[2] = [(1, 1), (2, 1), (2, 2)]

I've struggled to get a result like this without writting a really bad code:

    val0 = []
    val1 = []
    val2 = []
    for i in range(3):
        for j in range(3):
            if(map[i][j] == 0) : val0.append((i, j))
            if(map[i][j] == 1) : val1.append((i, j))
            if(map[i][j] == 2) : val2.append((i, j))

    data = []
    data.append(val0)
    data.append(val1)
    data.append(val2)
3
  • Why don't you show us your code so we can get an idea of where you are? Commented Apr 1, 2019 at 10:05
  • I'd be you i'd do 2-dimensionnal for loops to take value from your map and append them to result where you want. But, as @FChm said, if you want us to help you, you'll need to show us some code. Commented Apr 1, 2019 at 10:07
  • After your edit : It seems you struggle with your actual "position" within the 2-dimensionnal loops. Check Droid's answer Commented Apr 1, 2019 at 10:09

2 Answers 2

4

Iterate over the matrix and save where you see each value in a dict. That's your result.

retval = defaultdict(list)
for i in range(len(map)):
   for j in range(len(map[i])):
      val = map[i][j]
      retval[val].append((i,j))
print retval
Sign up to request clarification or add additional context in comments.

Comments

1

You can use some numpy methods:

import numpy as np
map = [[0, 1, 1], [0, 2, 1], [0, 2, 2]]
npmap = np.array(map)
[list(zip(*np.where(npmap==x))) for x in range(np.max(npmap)+1)]
#[[(0, 0), (1, 0), (2, 0)], [(0, 1), (0, 2), (1, 2)], [(1, 1), (2, 1), (2, 2)]]

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.