我正在尝试替换这个二维列表中的破折号来表示相邻的地雷数量
grid = [["-", "-", "-", "#", "#"],
["-", "#", "-", "-", "-"],
["-", "-", "#", "-", "-"],
["-", "#", "#", "-", "-"],
["-", "-", "-", "-", "-"]]
并按如下方式打印新网格:
1 1 2 # #
1 # 3 3 2
2 4 # 2 0
1 # # 2 0
1 2 2 1 0
这是我当前的Python代码
positions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0],[1, 1]]
mine = "#"
new_grid = [[[0, mine][count_two == mine] for count_two in row] for row in grid]
def minesweeper(grid):
count = 0
for count, value in enumerate(grid):
for count_two, value_two in enumerate(value):
for dr, dc in grid:
if value_two == mine:
if count+dr in range(len(grid)) \
and count_two+dc in range(len(value)):
new_grid[count][count_two] += \
grid[count+dr][count_two+dc] == mine
for row in new_grid:
for count_two in row:
print(count_two, end=" ")
print()
但是,它打印以下内容:
0 0 0 # #
0 # 0 0 0
0 0 # 0 0
0 # # 0 0
0 0 0 0 0
当我定义 new_grid 变量时,我可以看到第一个 [] 中的 0 导致相邻我的 0 不增加,但我不知道如何修复
你没有调用minesweeper():
positions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0],[1, 1]]
mine = "#"
new_grid = [[0, 0, 0, "#", "#"],
[0, "#", 0, 0, 0],
[0, 0, "#", 0, 0],
[0, "#", "#", 0, 0],
[0, 0, 0, 0, 0]]
def minesweeper(grid):
count = 0
for count, value in enumerate(new_grid):
for count_two, value_two in enumerate(value):
for dr, dc in positions:
if count+dr in range(len(new_grid))and count_two+dc in range(len(value)):
if new_grid[count+dr][count_two+dc] == mine and grid[count][count_two] != mine:
new_grid[count][count_two] += 1
minesweeper(new_grid)
for row in new_grid:
for count_two in row:
print(count_two, end=" ")
print()