我正在用Python创建一个迷宫遍历器。最初,我将迷宫txt文件作为列表读取,但无法逐行打印迷宫。给出了行和列的数目、入口的行和列以及出口的行和列。
我要说的是:
[['5', ' ', '5', ' ', '4', ' ', '1', ' ', '0', ' ', '1'], ['#', ' ', '#', '#', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', ' ', ' ', '#'], ['#', ' ', '#', '#', '#']]
我想要的是:
5 5 4 1 0 1
# ###
# # #
# # #
# #
# ###
我打印迷宫的测试代码:
#read MAZE and print
def readMaze(maze, filename):
mazeFile = open(filename, "r")
columns = mazeFile.readlines()
for column in columns:
column = column.strip()
row = [i for i in column]
maze.append(row)
maze =[]
readMaze(maze, "maze01.txt")
print maze
发布于 2016-12-03 01:05:48
如果您的maze
列表是这样的:
maze = [['5', ' ', '5', ' ', '4', ' ', '1', ' ', '0', ' ', '1'], ['#', ' ', '#', '#', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', ' ', ' ', '#'], ['#', ' ', '#', '#', '#']]
您可以使用join
和类似于下面的示例的for loop
来打印它并获得所需的打印输出:
for i in maze:
print("".join(i))
输出:
5 5 4 1 0 1
# ###
# # #
# # #
# #
# ###
发布于 2016-12-03 01:05:49
您只需打印整个列表,而不需要迭代它来打印您想要的字符。您需要使用for
循环,就像在readMaze
函数中一样,可以在顶级列表上迭代,并且在每个元素(这是一个字符列表)上,使用加入将字符连接到一个字符串中,然后打印出来,然后移到下一行。
# your input list has multiple nested sub-lists
l = [
['5', ' ', '5', ' ', '4', ' ', '1', ' ', '0', ' ', '1'],
['#', ' ', '#', '#', '#'],
['#', ' ', '#', ' ', '#'],
['#', ' ', '#', ' ', '#'],
['#', ' ', ' ', ' ', '#'],
['#', ' ', '#', '#', '#']
]
# so we iterate over them...
for sublist in l:
print(''.join(sublist)) # ...and concatenate them together before printing
输出:
5 5 4 1 0 1
# ###
# # #
# # #
# #
# ###
https://stackoverflow.com/questions/40943108
复制相似问题