[[+content_image]]
A
A
aab1372018-11-05 08:18:16
Python
aab137, 2018-11-05 08:18:16

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]]

You need to get a list of neighbors for each "cell", for example, for a given matrix it will be like this:
[[2,8,3], [4,2,8,6,5], [3,8,6], [4,3,8,7,0], [4,3,5,6,9,7,0,2], и т.д.]

I would like to do it as quickly as possible.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
Sergey Gornostaev, 2018-11-05
@aab137

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]))]

X
xmoonlight, 2018-11-05
@xmoonlight

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 question

Ask a Question

731 491 924 answers to any question