列表索引错误类型

时间:2015-11-10 15:03:54

标签: python runtime-error

这是我正在尝试运行的代码

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

1 个答案:

答案 0 :(得分:2)

查看https://github.com/apache/camel/blob/6dae060eeec8b49531df5d6828030f4ef037f6eb/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java以获取有关Python中二维数组的详细讨论。

基本上,python中的二维数组不像board [x,y]那样工作,它们实际上是数组的数组,如板[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", "*"

希望这有用!