从文件中读取文本迷宫,包含大量墙壁(#)和开口()。
迷宫需要被读入二维数组。
我无法弄清楚如何拆分每个'#'和''以便它们是分开的。
答案 0 :(得分:1)
只需调用list()
就可以将每个字符分别作为列表中的元素进行分割
from pprint import pprint as pp
def loadMaze(mazeName):
global grandList
grandList = []
with open(mazeName) as sourceList:
for line in sourceList:
eachList = list(line)
grandList.append(eachList)
pp(grandList)
答案 1 :(得分:0)
请勿拨打.split()
。
eachList = list(line.strip('\n'))
因为string.split()用于将字符串空格分隔成子字符串列表:
>>> "a bb ccc".split()
['a', 'bb', 'ccc']
或用字符分隔:
>>> "a/bb/ccc".split('/')
['a', 'bb', 'ccc']
list(some_string)将列出字符串中的字符:
>>> list("a, bb, ccc")
['a', ',', ' ', 'b', 'b', ',', ' ', 'c', 'c', 'c']
答案 2 :(得分:0)
叶氏!你几乎成功了,只是不要分开琴弦。
你可以轻松地做到这一点,
with open(mazeName) as sourceList:
for line in sourceList:
grandList.append(list(line))
pp(grandList)
或以你自己的方式:
with open(mazeName) as sourceList:
for line in sourceList:
grandList.append([c for c in line])
pp(grandList)