我是否可以更改此代码,以便产生可以存储为2d列表的输出?

时间:2019-01-24 15:03:20

标签: python list recursion 2d maze

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

我想将其存储到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 这样我就可以对其进行编辑。

2 个答案:

答案 0 :(得分:0)

这是我的解决方案。使用np.append函数将迷宫添加到二维数组中:

from random import randrange, shuffle
import numpy as np
w = 10
h = 10
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 = ""

twoD_matrix = np.append([hor[0]], [ver[0]], axis=0)

for i in range(1, len(hor)):
    twoD_matrix = np.append(twoD_matrix, [hor[i], ver[1]], axis = 0)


print(twoD_matrix)

或者,如果您希望使用列表列表,可以执行以下操作:

from random import randrange, shuffle
import numpy as np
w = 10
h = 10
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 = ""

twoD_list = []

for i in range(len(hor)):
    twoD_list.append(hor[i])
    twoD_list.append(ver[i])

print(twoD_list)

答案 1 :(得分:0)

您要做的只是在将-ya加入b的部分中做一个很小的更改。您需要具有其他变量s来存储2D列表:

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