蟒蛇给我"TypeError: list indices must be integers or slices, not tuple",我不知道为什么



我有这样的代码:

board = [[1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 1, 0], [1, 1, 0, 0, 1, 0], [1, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1]]

def print_board():
for line in board:
for char in line:
print(char, end=" ")
print()
print_board()
island_list = []
for y in range(len(board)):
for x in range(len(board[y])):
if board[y][x] == 1:
if (y, x) not in island_list:
if x == len(board[x]) - 1 or x == 0 or y == len(board)-1 or y == 0:
island_list.append((y, x))
List_to_add = []
for y in range(len(board)):
state = 0
for x in range(len(board[0])):
if board[y][x] == 1 and (y, x) not in island_list or state == 1 and (y, x) not in island_list:
List_to_add.append((y, x))
if (y, x) in island_list:
state = 1
if board[y][x] == 0:
state = 0
List_to_add = []
if (y, x) in island_list and board[y][x] == 1 or state == 1:
for x in List_to_add:
island_list.append(x)
List_to_add = []
for x in range(0, len(board[0])):
state = 0
for y in range(0, len(board)):
if state == 1:
for x in List_to_add:
island_list.append(x)
if board[y][x] == 1:
List_to_add.append((y, x))
if (y, x) in island_list:
state = 1
if board[y][x] == 0:
state = 0
List_to_add = []

print(island_list)

在这个程序中,我试图将连接到矩阵边缘的索引与未连接的索引分开,但当我试图访问矩阵中的索引时我得到第46行:if board[y][x] == 1:的TypeError。我觉得这很奇怪,因为我在这行上面用了同样的语句,却没有得到错误。如果你能帮我解决这个问题,我会很感激的。

当您正在运行循环

for x in range(0, len(board[0])):
state = 0
for y in range(0, len(board)):
if state == 1:
for x in List_to_add:
island_list.append(x)
if board[y][x] == 1:
List_to_add.append((y, x))
if (y, x) in island_list:
state = 1
if board[y][x] == 0:
state = 0
List_to_add = []

检查线

for x in List_to_add:

在这一行中,你使用x作为临时变量,在最后用元组重新初始化x,从而给你带来问题。

重命名这个变量。

相关内容

最新更新