python - 为世界生成读取文件的生命游戏 - 字符串索引超出范围问题
问题描述
就像标题说的那样,我正在用 Python 开发康威生命游戏的变体,它可以从文件中读取“世界”并从中生成起始世界。但是,在我的代码中,我在 while(aLine[currentCharacter] != NEWLINE) 这一行遇到了“字符串索引超出范围”的问题,我不知道为什么。
如果有帮助,在输入文件中“”被视为死细胞,“*”被视为活细胞。
感谢您的帮助,如果我应该提供任何其他信息,请告诉我
def fileReadWorld():
fileOK = False
world = []
row = 0
column = 0
while (fileOK == False):
try:
filename = input("Name of input file: ")
inputfile = open(filename,"r")
fileOK = True
aLine = inputfile.readline()
if(aLine == ""):
print("The file %s" %(filename), "is empty.")
fileOK = False
else:
aLine = inputfile.readline()
row = 0
while(aLine != ""):
currentCharacter = 0
world.append([])
while(aLine[currentCharacter] != "\n"):
world[row].append(aLine[currentCharacter])
currentCharacter = currentCharacter + 1
row = row + 1
aLine = inputfile.readline()
inputfile.close()
maxRows = row
maxColumns = len(world[0])
return(world, maxRows, maxColumns)
except IOError:
print("Problem reading from file %s" %(filename))
fileOK = False
我正在使用的输入文件是
*
*
***
(它应该显示为 10x10 网格)
解决方案
考虑这个具有相同结果的更简单的解决方案:
def main():
world = []
while True:
try:
filename = input("Name of input file: ")
for aLine in open(filename,"r")
world.append(list(aLine[:-1]))
if world:
maxRows = len(world)
maxColumns = len(world[0])
return world, maxRows, maxColumns
print("The file %s" %(filename), "is empty.")
except IOError:
print("Problem reading from file %s" %filename)
print(main())
推荐阅读
- node.js - [Koa]404 在通过路由器时
- c# - IRepository 和工作单元与急切加载
- c# - 将对象相互注入
- javascript - Chart.js 在单个 x 轴上垂直对齐的点
- google-cloud-platform - Google Cloud Composer 和 Google Cloud SQL 代理
- usb - 通过USB连接STM32F7和SIM7600
- kubernetes - 如何允许 Kubernetes 作业访问主机上的文件
- php - 更新/放置路线 - 不允许的方法
- c - 试图将元素附加到多维数组。尝试运行应用程序时抛出异常
- amazon-web-services - 如何找到亚马逊 MWS wsdl