慕尼黑的夜晚无繁华
就像@Aurel Bílý 提到的那样,您需要为特定情况添加四个相邻坐标:[Table[y - 1][x], Table[y + 1][x], Table[y, x - 1], Table[y, x + 1]].为此,您必须首先确保这些坐标有效并且不会引发IndexError异常。确保此坐标有效后,您可以安全地将它们添加到表中。下面的代码演示了这一点:Table=[['','','','',''], ['','','','',''], ['','','','',''], ['','','value','',''], ['','','','',''], ['','','','','']]def isInBounds(Table,x,y): return 0 <= x < len(Table) and 0 <= y < len(Table[0])def addValue(Table,x,y,value): if isInBounds(Table,x,y): Table[x][y] = valuedef addValuesAround(Table,x,y,value): addValue(Table,x-1,y,value) addValue(Table,x,y-1,value) addValue(Table,x+1,y,value) addValue(Table,x,y+1,value)addValuesAround(Table,3,2,1)for elem in Table: print(elem)这将返回:['', '', '', '', '']['', '', '', '', '']['', '', 1, '', '']['', 1, 'value', 1, '']['', '', 1, '', '']['', '', '', '', '']编辑:我想我明白了,使用我们的两个代码。请务必更改print函数的语法,因为您使用的是 Python 2.7 而我使用的是 Python 3.6:import randomdef isInBounds(Table,x,y): return 0 <= x < len(Table) and 0 <= y < len(Table[0])def addValue(Table,x,y,value): if isInBounds(Table,x,y): Table[x][y] = valuedef addValuesAround(Table,x,y,value): addValue(Table,x-1,y,value) addValue(Table,x,y-1,value) addValue(Table,x+1,y,value) addValue(Table,x,y+1,value)size=150if size%2==1: size+=1board = [[" " for i in range(size)] for i in range(size)] bombs = 25all_cells = ["nuke"] * bombs + [" "] * (size - bombs) random.shuffle(all_cells)board = [all_cells[i:i+10] for i in range(0, size, 10)]count=0for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == 'nuke': addValuesAround(board,i,j,"1")for item in board: print(item)这将给出一个像这样的板实例:[' ', ' ', ' ', ' ', '1', ' ', '1', ' ', '1', ' '][' ', ' ', ' ', '1', 'nuke', '1', 'nuke', '1', 'nuke', '1']['1', ' ', ' ', ' ', '1', ' ', '1', ' ', '1', '1']['nuke', '1', '1', '1', 'nuke', '1', ' ', ' ', '1', 'nuke']['1', '1', 'nuke', '1', '1', ' ', '1', ' ', ' ', '1'][' ', ' ', '1', ' ', ' ', '1', 'nuke', '1', ' ', ' '][' ', ' ', '1', ' ', ' ', '1', '1', ' ', ' ', ' '][' ', '1', 'nuke', '1', '1', 'nuke', '1', ' ', ' ', ' ']['1', 'nuke', '1', ' ', '1', '1', '1', ' ', '1', ' '][' ', '1', 'nuke', '1', 'nuke', '1', 'nuke', '1', 'nuke', '1']['1', 'nuke', '1', ' ', '1', ' ', '1', ' ', '1', ' '][' ', '1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '][' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', ' ', ' '][' ', '1', 'nuke', '1', ' ', '1', ' ', '1', ' ', ' '][' ', ' ', '1', ' ', '1', 'nuke', '1', 'nuke', '1', ' ']