如何在python的二维列表中求和所有邻居

时间:2018-10-09 13:52:46

标签: python list

对于python中的二维列表

grid = [[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15]]

如何对一个条目及其所有邻居(左,右,上和下)及其自身求和?对于grid[0][0],它是4 + 1 + 0 = 5;对于grid[0][1],它是0 + 2 + 5 + 1 = 8

谢谢您的回答,但是我们可以在不导入任何模块的情况下解决它吗?

3 个答案:

答案 0 :(得分:1)

可能最简洁的方法是使用2D convolution

In [1]: import numpy as np
In [2]: from scipy.signal import convolve2d
In [3]: kernel = np.array([[0, 1, 0],
   ...:                    [1, 1, 1],
   ...:                    [0, 1, 0]])
   ...:
In [4]: grid = [[ 0,  1,  2,  3],
    ...:         [ 4,  5,  6,  7],
    ...:         [ 8,  9, 10, 11],
    ...:         [12, 13, 14, 15]]
    ...:

In [5]: convolve2d(grid, kernel, mode='same')
Out[5]:
array([[ 5,  8, 12, 12],
       [17, 25, 30, 27],
       [33, 45, 50, 43],
       [33, 48, 52, 40]])

答案 1 :(得分:0)

grid = [[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15]]

# 4 for this grid, otherwise len() works
res = [[0] * 4 for i in range(4)]

# use this function to avoid bounds checking
def is_neighbor(x1, y1, x2, y2):
    if (x1 == x2 + 1 and y1 == y2) or (x1 == x2 - 1 and y1 == y2) or (x1 == x2 and y1 == y2 + 1) or (x1 == x2 and y1 == y2 -1):
        return True
    else:
        return False

# add numbers arounds point (x,y), including itself
def add_up(x, y):
    tf_map = [[0] * 4 for i in range(4)]
    for i in range(4):
        for j in range(4):
            if is_neighbor(x, y, i, j):
                tf_map[i][j] = grid[i][j]
    tf_map[x][y] = grid[x][y]
    sum = 0
    for row in tf_map:
        for item in row:
            sum += item
    res[x][y] = sum
    return res

# reconstruct the 2-D list
for i in range(4):
    for j in range(4):
        add_up(i, j)

print(res)
>>
[[5, 8, 12, 12], [17, 25, 30, 27], [33, 45, 50, 43], [33, 48, 52, 40]]

答案 2 :(得分:0)

许多编码难题中都提到了这一点。 一种简单的方法是:

grid = [[0,  1,  2,  3],
        [4,  5,  6,  7],
        [8,  9, 10, 11],
        [12, 13, 14, 15]]

x, y = 0, 0
neighbors = [(x, y), (x+1, y), (x-1, y), (x, y+1), (x, y-1)]

print(sum(grid[z][w] for z, w in neighbors
          if 0 <= z < len(grid) and 0 <= w < len(grid[0])))

简单但缓慢。