Like the title says, I've being working on a variant of Conway's Game of Life in python that can read a "world" and generate some elements from a file and generate the starting world from that. However开发者_高级运维, in my code, the world is being displayed as
([['*', ' ', ' ', ' ', ' ', ' '], ['*', '*', ' '], ['*', '*', '*'], ['*', '*', '*', '*'], ['*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*']], 10, 6)
When I am trying to get it to look like this as it is from the imported file.
*
**
***
****
*****
******
*******
********
*********
**********
I have no clue on how to get this program to display it properly as I have tried to edit around the list variables, but nothing I am doing is actually doing anything, as it either displays it wrong or just gives me an error. Can anyone here point me in the right direction?
Thank you for the help, and please let me know if there's any additional info I should provide
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())
Use str.join
and/or the sep
parameter to print()
:
>>> world, rows, columns = ([['*', ' ', ' ', ' ', ' ', ' '], ['*', '*', ' '], ['*', '*', '*'], ['*', '*', '*', '*'], ['*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*']], 10, 6)
>>> print(*(''.join(row) for row in world), sep='\n')
*
**
***
****
*****
******
*******
********
*********
*********
>>> print('\n'.join(''.join(row) for row in world))
*
**
***
****
*****
******
*******
********
*********
*********
>>> for row in world:
... print(*row, sep='')
...
*
**
***
****
*****
******
*******
********
*********
*********
You probably want something like this.
def main():
# get the file to read
filename = input("Name of input file: ")
# open, read, and close the file
with open(filename, "r") as f:
world = [list(line[:-1]) for line in f]
# get derived information
rows = len(world)
columns = max([len(i) for i in world])
world_printable = '\n'.join([''.join(i) for i in world])
return world, rows, columns, world_printable
world, rows, columns, world_printable = main()
print(world_printable)
If you ONLY want to print the file, you could just do,
def main():
# get the file to read
filename = input("Name of input file: ")
# open, read, and close the file
with open(filename, "r") as f:
for line in f.readlines():
print(line.strip())
main()
精彩评论