Python错误代码:IndexError:索引错误列表索引超出范围

2024-04-25 19:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python编写一个函数来模拟赛马。虽然没有赢家,但它会清除屏幕,显示马的列表(所有马的索引都从零开始)。然后,在我标记的行上,代码出错了。 我得到的索引错误列表超出范围。我尝试随机选择一匹马(随机选择一个索引号)并在值上加1。但我好像想不通!!你知道吗

while (no_winner):

    os.system("cls")

    print(horses)

    # randomly assign a horse to step forward
    rando = random.randint(1, HORSE_NUM)
    horses[rando] += 1  #######PROBLEM

    # if the horse exceeds the finish line, he wins
    if (steps > FINISH_LINE):

        winner = horses[index]
        no_winner = False

Tags: the函数no代码标记列表if屏幕
1条回答
网友
1楼 · 发布于 2024-04-25 19:25:41

你知道吗随机.randint()是包含的,因此如果您得到一个等于HORSE_NUM的随机整数,它将超出界限。试试看

rando = random.randint(0, HORSE_NUM - 1)

相关问题 更多 >