我有一个名为Matrix
的二维数组。数组中填充了一堆o
和c
。我试图逐个遍历数组元素。如果一个元素符合一组特定的规则,我想将该元素更改为N
。
下面是我这样做的代码。当我运行代码时,某些元素将替换为N
,但并非所有应替换的元素。
真的很感谢您的帮助,谢谢!
2D阵列:
https://nofile.io/f/74GXSntofsG/obstaclemapinput.txt
输出的2D数组:
https://nofile.io/f/ZhzK38x4Sqp/obstaclemap.txt
代码:
matrix_icrement_width = int(width/int(boxsize))
matrix_icrement_height = int(height/int(boxsize))
Matrix = [[0 for x in range(matrix_icrement_width)] for y in range(matrix_icrement_height)]
#The 2d array is populated however that code is long and irrelevant so I did not include it in my question
def traverse_matrix():
for i in range (0,matrix_icrement_width):
for j in range (0,matrix_icrement_height):
if Matrix[i][j]== "o":
#if u r on a wall, dont do anything
break
if Matrix[i][j-1] == "o":
#if u were on a wall, but not anymore
Matrix[i][j] = "N"
if Matrix[i+1][j] == "c":
#if the space below u is a path
Matrix[i][j] = "N"
if Matrix[i][j+1] == "o":
#if the space infront of u is a wall
Matrix[i][j] = "N"
def printMatrix():
f = open('obstaclemap.txt', 'w')
f.write('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in Matrix]))
f.close()
traverse_matrix()
printMatrix()
答案 0 :(得分:1)
我认为该问题是由于粗心地使用break
而不是continue
造成的。尝试替换它,让我知道结果。
matrix_icrement_width = int(width/int(boxsize))
matrix_icrement_height = int(height/int(boxsize))
Matrix = [[0 for x in range(matrix_icrement_width)] for y in range(matrix_icrement_height)]
#The 2d array is populated however that code is long and irrelevant so I did not include it in my question
def traverse_matrix():
for i in range (0,matrix_icrement_width):
for j in range (0,matrix_icrement_height):
if Matrix[i][j]== "o":
#if u r on a wall, dont do anything
continue #Modify this
if Matrix[i][j-1] == "o":
#if u were on a wall, but not anymore
Matrix[i][j] = "N"
if Matrix[i+1][j] == "c":
#if the space below u is a path
Matrix[i][j] = "N"
if Matrix[i][j+1] == "o":
#if the space infront of u is a wall
Matrix[i][j] = "N"
def printMatrix():
f = open('obstaclemap.txt', 'w')
f.write('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in Matrix]))
f.close()
traverse_matrix()
printMatrix()