为战舰创建并初始化5x5网格 [英] Create and initialize 5x5 grid for Battleships
问题描述
所以我刚刚完成了CodeAcademy Battleship问题的一部分,并提交了正确的答案,但是在理解为什么它是正确的时遇到了困难.
So I just completed a section of CodeAcademy Battleship problem, and have submitted a correct answer but am having trouble understanding why it is correct.
这个想法是要建立一个5x5的网格板,并用"O"填充.我使用的正确代码是:
The idea is to build a 5x5 grid as a board, filled with "O's". The correct code I used was:
board = []
board_size=5
for i in range(board_size):
board.append(["O"] *5)
但是,我对为什么没有在一行中创建25个"O"感到困惑,因为我从未指定要迭代到另一行.我尝试过
However I'm confused as to why this didn't create 25 "O's" in one single row as I never specified to iterate to a separate row. I tried
for i in range(board_size):
board[i].append(["O"] *5)
但是这给了我错误:IndexError: list index out of range
.谁能解释为什么第一个是正确的而不是第二个呢?
but this gave me the error: IndexError: list index out of range
. Can anyone explain why the first one is correct and not the second one?
推荐答案
["O"]*5
这将创建一个大小为5的列表,并用"O"填充:["O", "O", "O", "O", "O"]
This creates a list of size 5, filled with "O": ["O", "O", "O", "O", "O"]
board.append(["O"] *5)
这会将以上列表追加(添加到列表的末尾)到board [].循环执行5次将创建一个包含上述列表中的5个的列表.
This appends (adds to the end of the list) the above list to board[]. Doing this 5 times in a loop creates a list filled with 5 of the above lists.
[["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"]]
您的代码不起作用,因为列表未在python中用大小初始化,因此它只是从一个空容器[]
开始.要使您的工作正常进行,您可以完成以下操作:
Your code did not work, because lists are not initialized with a size in python, it just starts as an empty container []
. To make yours work, you could have done:
board = [[],[],[],[],[]]
并在您的循环中:
board[i] = ["O"]*5
这篇关于为战舰创建并初始化5x5网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!