Accessing neighbour indices in a particular element of an array (python)

Question:

I have a two dimensional list like :

data = [[0,0,0,0,0,1,0,0,0,0], [0,1,0,0,0,0,0,0,0,0]]

How can I access the index of the neighbours, where the value equals 1?

Expected output:

[[4, 5, 6], [0, 1, 2]]

For example, the indices of an array data in first row at value 1 is 5, so I need to access its left and right side neighbour indices like 4 and 6. Same way for row 2.

Asked By: Bhar Jay

||

Answers:

One efficient solution is using FOR loops:

for i in range(2):
    for j in range(10):
        if a[i][j]==1:
            print(str(i)+' '+str(j))

If using lists, here is a one approach which identifies the indexes of the neighbours of 1. As a caveat, this will fail with a index out of range, if the 1 value is the first of last element in the list.

Input:

data = [[0,0,0,0,0,1,0,0,0,0], [0,1,0,0,0,0,0,0,0,0]]

Example:

[[idx-1, idx, idx+1] for i in data for idx, j in enumerate(i) if j == 1]

Output:

[[4, 5, 6], [0, 1, 2]]
Answered By: S3DEV

If I understand description well (please clarify) , maybe you can try this one. Additionally, you can check edge case where there is no 1, or no left or right .

import numpy as np

a = np.array([
 [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 
 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]])

if __name__ == "__main__":
  indices = np.where(a == 1)[1]
  indices = indices.reshape(-1,1)
  indices = np.concatenate([indices-1,indices,indices+1],-1)
  print(indices)
Answered By: TaQ
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.