简体   繁体   中英

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. 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,

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.

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. 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__ . You can simply use 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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