社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Simon Z.

Simon Z. 最近回复了
6 年前
回复了 Simon Z. 创建的主题 » 如何在python中求二维列表中所有邻居的和
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]]