【问题标题】:Game of Life with file read for world generation. How to get file to display world properly?为世界生成读取文件的生命游戏。如何让文件正确显示世界?
【发布时间】:2022-12-18 16:09:25
【问题描述】:

正如标题所说,我一直在研究 Conway 的 Python 生命游戏变体,它可以读取“世界”并从文件中生成一些元素并从中生成起始世界。但是,在我的代码中,世界显示为

([['*', ' ', ' ', ' ', ' ', ' '], ['*', '*', ' '], ['*', '*', '*'], ['*', '*', '*', '*'], ['*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*']], 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())

【问题讨论】:

  • 这个输入应该是什么意思?您希望它在展示时看起来像什么?
  • 像三角形显示
  • @Samwise 在下面有正确答案。看来你也需要像这样更新你的代码,maxColumns = max([len(i) for i in world[0]])
  • 我会放在哪里?对不起,如果我听起来很沉闷,但它不适合我

标签: python list function file variables


【解决方案1】:

使用str.join和/或sep参数到print()

>>> world, rows, columns = ([['*', ' ', ' ', ' ', ' ', ' '], ['*', '*', ' '], ['*', '*', '*'], ['*', '*', '*', '*'], ['*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*']], 10, 6)
>>> print(*(''.join(row) for row in world), sep='
')
*
**
***
****
*****
******
*******
********
*********
*********
>>> print('
'.join(''.join(row) for row in world))
*
**
***
****
*****
******
*******
********
*********
*********
>>> for row in world:
...     print(*row, sep='')
...
*
**
***
****
*****
******
*******
********
*********
*********

【讨论】:

  • 如果世界:maxRows = len(world) maxColumns = len(world[0]) print(*(''.join(row) for row in world), sep=' ') return world, maxRows, maxColumns print("The file %s" %(filename), "is empty.") except IOError: print("Problem reading from file %s" %(filename)) 像这样?因为我现在都得到了,而不是我想要的数组。
  • 我不知道你想在那里问什么 - 但如果 world 具有你在原始问题中发布的值,那么上面的代码应该按照你想要的方式打印它。
  • 哦,我想我现在明白了。不要在函数内部打印,也不要只打印main() 返回的内容。执行world, rows, cols = main(),然后执行代码以正确格式打印world
  • 我在 (maxColumns = len(world[0]) 和 (return world, maxRows, maxColumns) 之间插入代码,但结果显示是三角形和初始长线的显示。我把它放在哪里,这样它就不会显示错误的?
  • tl;dr:不要打印你不想打印的东西。 :)
猜你喜欢
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多