Finding neighbours in a two-dimensional array

后端 未结 20 1224
忘了有多久
忘了有多久 2020-11-30 02:02

Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding

20条回答
  •  天涯浪人
    2020-11-30 02:24

    although nested for loops in list comprehensions is a bit ugly this is shorter:

    def neighbours(m, i, j):
        return [m[x][y] for x in [i-1,i,i+1] for y in [j-1,j,j+1] if x in range(0,len(m)) and y in range(0,len(m[x])) and (x,y) != (i,j)]
    

提交回复
热议问题