简体   繁体   English

战舰5x5网格中的行无法正确显示

[英]rows in battleship 5x5 grid not displaying accurately

I am supposed to ask this question on the codecademy forum, but there is a limit to the number of questions one may ask in a single day. 我应该在codecademy论坛上问这个问题,但是一天中可能要问的问题数量是有限的。 If you wish to answer, I would appreciate it: 如果您想回答,我将不胜感激:

Hello, 你好,

I have written this code with the intention to display the required 5x5 batleship grid, 我编写此代码的目的是为了显示所需的5x5战斗格,

The intended grid should look like this: 预期的网格应如下所示:

['O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O']

The Output my code is displaying is: 我的代码显示的输出是:

[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
None

I cannot correct this mistake on my own. 我无法自行纠正此错误。 I want the output to display correctly. 我希望输出正确显示。 I don't know where to place a line break character to display this grid properly. 我不知道在何处放置换行符以正确显示此网格。 The system is saying way to go, but in fact the output is not displaying properly at all: 系统正在说要走的路,但实际上输出根本无法正确显示:

board = []

#for j in range(0,5):
for i in range(0,5):

    board.append(["O"]*5)
            #board.append("O")

print board

Thanks for taking the time to respond, I do appreciate your effort. 感谢您抽出宝贵的时间回复,非常感谢您的努力。

When you print out a nested list in Python, it all comes out on one line. 当您在Python中打印出嵌套列表时,它们全部都显示在一行上。

To print one list per line, for loop through them, so that each list is prined on its own line. 每行打印一个列表,以循环浏览它们,以便使每个列表位于其自己的行上。

for row in board:
    print(row)

you have to iterate the lists within your board and print them one row (ie. one list) at a time like this: 您必须迭代电路板上的列表,并一次将它们打印成一行(即一个列表),如下所示:

for item in board:
    print (item)

You seem to be using Python 2. Therefore, what I suggest you do, if you want to print your list outside of your loop, the way you are trying to do it. 您似乎正在使用Python2。因此,如果您想在循环之外打印列表,则我建议您这样做。 Do this: 做这个:

>>> from __future__ import print_function
>>> print(*board, sep="\n")
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']

If you are using Python 3, you don't need to import from __future__ . 如果您使用的是Python 3,则无需从__future__导入。 You can simply use print(*board, sep="\\n") . 您可以简单地使用print(*board, sep="\\n")

Full demo: 完整演示:

In [5]: from __future__ import print_function

In [6]:

In [6]: board = []

In [7]: for i in range(0,5):
   ...:
   ...:         board.append(["O"]*5)
   ...:

In [8]: print(*board, sep="\n")
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM