Python实现Conway's Game of Life:读取文件后如何正确显示世界?
Conway生命游戏Python程序输出格式调整方案
问题现状
你开发的Conway生命游戏变体程序,从文件读取初始世界数据后,当前输出是嵌套列表组成的元组:
([['*', ' ', ' ', ' ', ' ', ' '], ['*', '*', ' '], ['*', '*', '*'], ['*', '*', '*', '*'], ['*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*']], 10, 6)
但期望输出和导入文件一致的格式:
* ** *** **** ***** ****** ******* ******** ********* **********
你的当前代码:
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())
解决步骤
避免直接打印main函数的返回值
main函数返回的是包含world、行数、列数的元组,直接print会输出元组的默认字符串表示,这就是你当前看到的嵌套列表格式。需要单独提取world并处理输出。将嵌套列表转换为字符串逐行打印
world中的每个子列表对应文件中的一行,用''.join(row)把列表中的字符拼接成字符串,再逐行打印即可还原文件格式。优化行读取逻辑(可选)
原代码中aLine[:-1]会切掉最后一个字符,若文件最后一行没有换行符,会误删有效字符。建议改用aLine.rstrip('\n')只去掉换行符,保留行内所有有效字符。
修改后的代码
def main(): world = [] while True: try: filename = input("Name of input file: ") with open(filename,"r") as f: # 使用with语句自动关闭文件,更规范 for aLine in f: # 只移除换行符,保留行内其他字符 world.append(list(aLine.rstrip('\n'))) if world: maxRows = len(world) maxColumns = len(world[0]) return world, maxRows, maxColumns print(f"The file {filename} is empty.") except IOError: print(f"Problem reading from file {filename}") # 处理输出 result = main() if result: world, _, _ = result for row in world: print(''.join(row))
说明
- 使用
with open(...)是Python操作文件的规范写法,能确保文件自动关闭,避免资源泄漏。 ''.join(row)将每行的字符列表拼接成完整字符串,完美还原文件中的行格式。- 提取world后用
_占位忽略行数和列数,如果后续需要用到这两个值,可以替换成实际变量名。
内容的提问来源于stack exchange,提问作者Dream Cloud
相关产品推荐
相关产品推荐

