索引 1 超出 Python 中大小为 1 的轴 0 的范围

问题描述

对于大学作业,我被要求将 1 行文本文件转换为二维数组。但是,当我运行该程序时,出现此错误

(venv) D:\Uni Stuff\Year 2\AIGP\Assignment\PYTHONASSIGNMEN>python astar.py
Input file name: Lab9TerrainFile1.txt
Traceback (most recent call last):
  File "D:\Uni Stuff\Year 2\AIGP\Assignment\PYTHONASSIGNMEN\astar.py",line 129,in <module>
    main()
  File "D:\Uni Stuff\Year 2\AIGP\Assignment\PYTHONASSIGNMEN\astar.py",line 110,in main
    number_of_rows = maze_file[1]
IndexError: index 1 is out of bounds for axis 0 with size 1

这是生成迷宫的代码

def main():

    maze_file = open(input("Input file name: "),"r").readlines()

    maze_file = np.array([maze_file])

    number_of_columns = maze_file[0]

    number_of_rows = maze_file[1]

    maze_column = np.array_split(maze_file[2:8],number_of_columns)

    maze_row = np.array_split(maze_file[2:8],number_of_rows)

    maze = np.concatenate([maze_column][maze_row])

    start = np.where(maze == 2)

    end = np.where(maze == 3)

    maze_file.close()

    path = astar(maze,start,end)
    print(path)

任何帮助将不胜感激,谢谢!

解决方法

您可以通过运行以下代码检查数组maze_file的大小来测试这一点。

print(len(maze_file))

如果返回 1,则表示它只有 1 个元素。

maze_file[0] 表示您正在获取第一个元素。因此,方括号之间的索引为 0。当您指定 maze_file[1] 时,它会尝试获取不存在的第二个元素。因此错误索引超出范围。

查看您的代码,您似乎正在尝试获取数组的列数和行数。您可以使用以下代码。

number_of_columns = len(maze_file)
number_of_rows = len(maze_file[0])