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

时间:2016-05-11 23:53:50

标签: python random indexing

我正在尝试用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

1 个答案:

答案 0 :(得分:1)

random.randint()是包含的,所以如果你得到一个等于HORSE_NUM的随机整数,它将超出界限。尝试

rando = random.randint(0, HORSE_NUM - 1)
相关问题