1

I have an object at location (x, y, z) and I want a list of its neighbouring coordinates. The objects 6 neighbours are located at plus or minus 1 in each direction. My list of coordinates would look like:

[[x+1, y, z], [x-1, y, z], [x, y+1, z], [x, y-1, z], [x, y, z+1], [x, y, z-1]]

Any smart (neat) ways of doing this in python?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
pb.
  • 125
  • 1
  • 7
  • Why don't just return the whole list? It has only 6 elements. – wong.lok.yin Jul 08 '21 at 09:14
  • 1
    Using this exact code should work. What's the problem? – mkrieger1 Jul 08 '21 at 09:23
  • Returning the list you gave is straight forward and neat in my opinion. – Ram Jul 08 '21 at 09:25
  • What are the boundary conditions? What should be the neighbors for (0,0,0) point? – alex Jul 08 '21 at 09:51
  • Does this answer your question? [Determining neighbours of cell two dimensional list](https://stackoverflow.com/questions/1620940/determining-neighbours-of-cell-two-dimensional-list) (the answers can be easily modified for N dimensions) – alex Jul 08 '21 at 09:57
  • As many of you pointed out, I got caught up in making the code 'smart' and overcomplicated it. @alex Yeah doing this does go outside boundary layers but I am using this list to create a list of neighbours (as objects not their location) – pb. Jul 08 '21 at 10:03

2 Answers2

1

This may not be the most pretty way, but if you need it for a function that repeats this operations then it should be just fine.

from copy import copy

point = [1,4,7]
neighbours = list()

for dim in range(len(point)):
    for shift in range(-1,2,2):
        neighbour = copy(point)
        neighbour[dim] += shift
        neighbours.append(neighbour)
0

My attempt using numpy:

import numpy as np
x=2.3
y=-4.5
z=1.9

my_points = np.repeat(np.array([[x,y,z]]),6,axis=0)
res = my_points + np.vstack((np.eye(3),-np.eye(3)))

print(res)

output:

[[ 3.3 -4.5  1.9]
 [ 2.3 -3.5  1.9]
 [ 2.3 -4.5  2.9]
 [ 1.3 -4.5  1.9]
 [ 2.3 -5.5  1.9]
 [ 2.3 -4.5  0.9]]

you could use res.tolist() to get a list of lists instead.

output:

[[3.3, -4.5, 1.9], [2.3, -3.5, 1.9], [2.3, -4.5, 2.9], [1.2999999999999998, -4.5, 1.9], [2.3, -5.5, 1.9], [2.3, -4.5, 0.8999999999999999]]
joostblack
  • 2,465
  • 5
  • 14