python - list[var-1] 最后而不是抛出 IndexError?
问题描述
我知道这很可能是一个相对简单的问题来回答,但我已经坚持了一段时间了。我正在用 Python 创建一个迷宫求解算法。迷宫是这样形成的(0 = 墙壁,1 = 空间)。我将每一行存储为一个嵌套列表:
data = [
[0,0,0,0,0,0,0,1,0,0,0],
[0,1,1,1,0,1,0,1,1,1,0],
[0,1,0,1,0,1,0,1,0,1,0],
[0,1,0,1,1,1,0,1,0,1,0],
[0,1,0,0,0,1,0,1,0,0,0],
[0,1,1,1,0,1,0,1,1,1,0],
[0,1,0,1,0,1,0,0,0,1,0],
[0,1,0,1,0,1,1,1,0,1,0],
[0,1,0,1,0,0,0,1,0,1,0],
[0,1,0,1,1,1,0,1,1,1,0],
[0,0,0,0,0,1,0,0,0,0,0]
]
为了便于查看,我的程序将该数据转换为:
◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎
◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎
找到一个空间surrounding_spaces
对我的程序的成功至关重要,因为我用它来寻找死胡同。然而,迷宫的开口可能被程序认为是死路,因为只有一种方法可以到达开口。为了解决这个问题,我依靠程序抛出一个IndexError
inget_surrounding()
以便开口中的一个项目surrounding_spaces
是None
.
在main()
中,我遍历每个等于1
程序可以占用的有效空间的空间。
def main():
row_ind = 0
for row in data:
space_ind = 0
for space in row:
if space == 1:
get_surrounding(row_ind, space_ind)
space_ind += 1
row_ind += 1
在get_surrounding()
中,我list
用surrounding_spaces
当前的row
. 这是我依赖的地方,IndexError
以便程序意识到这是一个开放而不是死胡同:
def get_surrounding(row, space):
try:
left = data[row][space - 1]
except:
left = None
try:
right = data[row][space + 1]
except:
right = None
try:
up = data[row - 1][space]
except:
up = None
try:
down = data[row + 1][space]
except:
down = None
surrounding_spaces = [left, right, up, down]
print("[" + str(row) + ", " + str(space) + "]:" + str(surrounding_spaces))
这个输出是完全正确的。最后的surrounding_spaces
开口是:row
data
[0, 0, 1, None]
但是,顶行是一个例外 ( data[0]
)。它确实有一个开口data[0][7]
。当up
变量设置在 中时get_surrounding()
,它将第一行视为最后一行,因为data[row-1][space]
本质上是data[-1][space]
as row = 0
。-1
用作索引获取last
a 的项目list
,我不想将其视为最后一个row
。就我而言,当top row
被迭代时,我想data[row-1][space]
抛出一个,因为之前IndexError
没有row
in 。如果有更简单的方法来实现这一点,欢迎提出任何建议。data
row0[0]
期望的输出
[0, 7]:[0, 0, None, 1]
[10, 5]:[0, 0, 1, None]
实际输出
# lists are formed like so: [left, right, up, down]
# the up value in the first list should be None, but it is 0 because when the up value is set the program treated
[0, 7]:[0, 0, 0, 1]
[10, 5]:[0, 0, 1, None]
笔记
为了翻译数据以便于查看,我使用了一个自定义类:
class MazeData:
def __init__(self, data):
self.data = data
def display(self):
data = self.data
length = len(data[0])
prettified_data = []
space_ids = {0:"◼︎", 1:" ", 2:"@", 3:"•"}
for row in data:
line = []
for space in row:
line.append(space_ids.get(space))
prettified_data.append(line)
for row in prettified_data:
print(" ".join(row))
您可以通过这种方式初始化和显示板:
board = MazeData(data)
board.display()
解决方案
推荐阅读
- r - 根据行日期生成列
- python - 如何在 M1 (Apple Silicon / Darwin-arm64) 上安装和导入 Scipy、Numpy、NumExpr 等?
- jenkins - 如何从詹金斯获得“视图”名称?
- php - Angular 7 和 laravel-echo
- python - 找不到 Pyodbc Microsoft Access 驱动程序
- firebase - React native iOS - 在应用程序第二次打开或第一次启动应用程序未收到通知之前无法收到任何通知
- arduino - 无法在nodemcu esp8266上同时控制L298n和Ac Light Dimmer
- logback - 如何创建自定义 logback 转换规则(不是 xml)?
- python - 在 Python 3 中运行 `tf.config.run_functions_eagerly(True)`?
- linq - 需要 EF Core LINQ 查询专家