Python 从if语句-迷宫解决软件中删除索引器

Python 从if语句-迷宫解决软件中删除索引器,python,list,maze,Python,List,Maze,所以我想编写一个迷宫解决程序,但我导入迷宫已经失败了。这是我的代码: def import_maze(filename): temp = open(filename, 'r') x, y = temp.readline().split(" ") maze = [[0 for x in range(int(y))] for x in range(int(x))] local_counter, counter, startx, starty = 0, 0, 0, 0

所以我想编写一个迷宫解决程序,但我导入迷宫已经失败了。这是我的代码:

def import_maze(filename):
    temp = open(filename, 'r')
    x, y = temp.readline().split(" ")
    maze = [[0 for x in range(int(y))] for x in range(int(x))]
    local_counter, counter, startx, starty = 0, 0, 0, 0
    temp.readline()
    with open(filename) as file:
        maze = [[letter for letter in list(line)] for line in file]

    for i in range(1, int(y)):
        for z in range(0, int(x)):
            if maze[i][z] == '#':
                local_counter += 1
            if local_counter < 2 and maze[i][z] == " ":
                counter += 1
            if maze[i][z] == 'K':
                startx, starty = i, z
        local_counter = 0

    return maze, startx, starty, counter


maze, startx, starty, counter = import_maze("kassiopeia0.txt")

print(counter, "\n", startx, ":", starty, "\n", maze)

Sry代表我的英语。

您在kassiopeia0.txt的标题行中指定了一个6×9的迷宫,但文件的其余部分包含一个9×6的迷宫


交换6号和9号,迷宫的读数应该很好。对我来说确实如此。

@Luke是对的。我建议您使用以下代码:

def import_maze(filename):

    with open(filename) as f:
        maze = [[letter for letter in line.strip()] for line in f.readlines() if line.strip()]

    local_counter, counter, startx, starty = 0, 0, 0, 0

    for y, row in enumerate(maze):
        for x, cell in enumerate(row):
            if cell == '#':
                local_counter += 1

            elif local_counter < 2 and cell == ' ':
                counter += 1

            elif cell == 'K':
                startx, starty = x, y

        local_counter = 0

    return maze, startx, starty, counter

嘿,非常感谢你,也感谢@Luke=D
6 9
#########
#  #    #
#  # #  #
#  K #  #
#    #  #
#########
def import_maze(filename):

    with open(filename) as f:
        maze = [[letter for letter in line.strip()] for line in f.readlines() if line.strip()]

    local_counter, counter, startx, starty = 0, 0, 0, 0

    for y, row in enumerate(maze):
        for x, cell in enumerate(row):
            if cell == '#':
                local_counter += 1

            elif local_counter < 2 and cell == ' ':
                counter += 1

            elif cell == 'K':
                startx, starty = x, y

        local_counter = 0

    return maze, startx, starty, counter
#########
#  #    #
#  # #  #
#  K #  #
#    #  #
#########