Py学习  »  Python

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

Simon Z. • 5 年前 • 1401 次点击  

对于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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39823
 
1401 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Simon Z.
Reply   •   1 楼
Simon Z.    6 年前
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]]
scnerd
Reply   •   2 楼
scnerd    6 年前

可能最简洁的方法是使用 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]])