gpt4 book ai didi

python - 列出索引类型错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:07 24 4
gpt4 key购买 nike

这是我要运行的代码

import random
def createBoard(rows, columns, mines):
board = [["C" for row in range(rows)],[" " for col in range(columns)]]
for i in range(0, mines):
board[[int(random.randrange(rows))],[int(random.randrange(columns))]] = "C", "*"
return board
createBoard(9, 12, 10)
board = board
print(board)

这是我得到的错误

Traceback (most recent call last):
File "C:\Users\Josh\Desktop\Python\createBoard.py", line 7, in <module>
createBoard(9, 12, 10)
File "C:\Users\Josh\Desktop\Python\createBoard.py", line 5, in createBoard
board[[int(random.randrange(rows))],[int(random.randrange(columns))]] = "C", "*"
TypeError: list indices must be integers, not tuple

最佳答案

查看 How to define two-dimensional array in python有关 Python 中二维数组的详细讨论。

基本上,python 中的二维数组不像 board[x, y] 那样工作,它们实际上是 board[x][y] 中的数组数组。

你需要重构你的代码

for i in range(0, mines):
board[[int(random.randrange(rows))],[int(random.randrange(columns))]] = "C", "*"

看起来更像

for i in range(0, mines): 
boardfor i in range(0, mines):
board[int(random.randrange(rows))][int(random.randrange(columns))]] = "C", "*"

希望这对您有所帮助!

关于python - 列出索引类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33633048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com