我在代码大战中输入代码时遇到此错误。 “回溯:在模块中 在damaged_or_sunk中 IndexError:列表索引超出范围“。但是,当我在spyder3中尝试我的代码时,它工作正常。但是没有关于函数damaged_or_sunk中此错误的位置的指示器。
def damaged_or_sunk (board, attacks):
a = sum(x.count(1) for x in board)
b = sum(x.count(2) for x in board)
c = sum(x.count(3) for x in board)
a1 = 0
b1 = 0
c1 = 0
points = 0
sunk = 0
damaged = 0
not_touched = 0
for each in attacks:
rand_row = each[0]
rand_col = each[1]
if board[rand_row][rand_col] == 1:
a1 += 1
elif board[rand_row][rand_col] == 2:
b1 += 1
elif board[rand_row][rand_col] == 3:
c1 += 1
else:
pass
if a1 == a:
points += 1
sunk += 1
elif a1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if b1 == b:
points += 1
sunk += 1
elif b1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if c1 == c:
points += 1
sunk += 1
elif c1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
return '{\'sunk\': %s, \'damaged\': %s, \'not_touched\': %s, \'points\': %s}' %(sunk, damaged, not_touched, points)
答案 0 :(得分:0)
attacks
中的情侣包含(x, y)
坐标,这些坐标必须是列表索引。
我假设它们是随机生成的,请确保:
0 <= x < len(board[0])
0 <= y < len(board)
all( len(board[0]) == len(board[row]) for row in board)