计算 2d 列表中周围方块中的符号数 python

Calculating how many symbols in surrounding squares in 2d list python

我在 python 课程的介绍中有一个作业,我必须创建一个使用循环遍历二维列表的函数,当给定 x 和 y 坐标时,它会计算其中有多少个“N”所选方块的周围方块。 x 和 y 可以在任何地方,并且不允许它们越过列表的边界。出于某种原因,课程 material 似乎非常缺乏,我找不到任何可以帮助我入门的内容。我应该如何使该功能发挥作用?

函数的参数必须是(x,y,列表) 该函数应假定您不在“N”上,但如果您在“N”上,它也算作那个。

如果有人能给我一些入门提示,那就太好了。

list = [['N', ' ', ' ', ' ', ' '],
        ['N', 'N', 'N', 'N', ' '],
        ['N', ' ', 'N', ' ', ' '],
        ['N', 'N', 'N', ' ', ' '],
        [' ', ' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' ', ' ']]

     

根据这段代码,您可以计算出列表中有多少 N:

list_ = [['N', ' ', ' ', ' ', ' '],
        ['N', 'N', 'N', 'N', ' '],
        ['N', ' ', 'N', ' ', ' '],
        ['N', 'N', 'N', ' ', ' '],
        [' ', ' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' ', ' ']]
count = 0
for a in list_:
    for b in a:
        if b == 'N':
            count += 1
print(count)

从问题中不清楚提供的 x 和 y 坐标是否将是围绕边缘且相邻元素少于 8 个的元素。

如果 x 坐标的范围是 1len(row) - 1 并且 y 坐标的范围是 1len(column)-1 那么你可以循环遍历每个二维列表中的行,然后是该行中的每个元素,然后检查该元素是否等于 'N'。这可以这样解决:

def adjacent_count(x, y, list_2d):
    count = 0
    for row in list_2d[x-1:x+2]:
        for element in row[y-1:y+2]:
            if element == 'N':
                count += 1
    return count

或者在一行中使用列表理解:

def adjacent_count(x, y, list_2d):
    return sum([1 if element == 'N' else 0 for row in list_2d[x-1:x+2] for element in row[y-1:y+2]])

编辑:现在知道 x 和 y 坐标的范围可以从 0len(rows)len(cols) 并且函数不应该换行到数组可以使用下面的代码。现在,代码会在尝试访问下一个数组元素之前检查它是否超出列表范围。

def adjacent_count(x, y, list_2d):
    no_rows, no_cols = len(list_2d), len(list_2d[0])
    count = 0
    for i in range(x-1, x+2):
        for j in range(y-1, y+2):
            if i < no_cols and j < no_rows:
                if list_2d[j][i] == 'N':
                    count += 1
    return count