Create and initialize 5x5 grid for Battleships(为战舰创建和初始化 5x5 网格)
问题描述
所以我刚刚完成了 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 网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为战舰创建和初始化 5x5 网格
基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01