所以我刚刚完成了 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 网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!