Answer the question
In order to leave comments, you need to log in
[[+content_image]]
How to determine neighbors in a two-dimensional list?
There is a square matrix, for example,
[[4,3,5],
[2,8,6],
[0,7,9]]
[[2,8,3], [4,2,8,6,5], [3,8,6], [4,3,8,7,0], [4,3,5,6,9,7,0,2], и т.д.]
Answer the question
In order to leave comments, you need to log in
def neighbors(x):
def in_bounds(i, j, x):
return 0 <= i < len(x) and 0 <= j < len(x[0])
return [[x[i + di][j + dj] for di in (-1, 0, 1)
for dj in (-1, 0, 1)
if in_bounds(i + di, j + dj, x) and (di != 0 or dj != 0)]
for i in range(len(x))
for j in range(len(x[0]))]
Make a linear array (bit block) and calculate using integer division and remainder in desired increment (+/- 1).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question