我是否可以更改此代码以生成可以存储为二维列表的输出?

我可以用这段代码打印一个随机迷宫:


我想将其存储到 2d 列表中,以便我可以对其进行编辑。


我曾尝试编辑自己,但此代码旨在仅用于打印,仅此而已。


def random_maze(w = 16, h = 8):

    vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]

    ver = [["|  "] * w + ['|'] for v in range(h)] + [[]]

    hor = [["+--"] * w + ['+'] for v in range(h + 1)]


    def go(x, y):

        vis[y][x] = 1


        d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]

        shuffle(d)

        for (xx, yy) in d:

            if vis[yy][xx]: continue

            if xx == x: hor[max(y, yy)][x] = "+  "

            if yy == y: ver[y][max(x, xx)] = "   "

            go(xx, yy)


    go(randrange(w), randrange(h))


    s = ""

    for (a, b) in zip(hor, ver):

        s += ''.join(a + ['\n'] + b + ['\n'])

    return s

我希望代码输出像 [['+--', '+--'....etc 这样我可以编辑它。


UYOU
浏览 152回答 2
2回答

尚方宝剑之说

您所要做的就是对加入a和b进入的部分进行小的更改s。您需要有一个额外的变量matrix来存储二维列表:s = ""matrix = []for (a, b) in zip(hor, ver):    s += ''.join(a + ['\n'] + b + ['\n'])    matrix.append(a)    matrix.append(b)return s, matrix最后你可以检索这样的结果:stringMatrix, matrix = random_maze()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python