【问题标题】:Python Error code: IndexError: index error list index out of rangePython错误代码:IndexError:索引错误列表索引超出范围
【发布时间】:2016-05-11 23:53:49
【问题描述】:

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

【问题讨论】:

标签: python random indexing


【解决方案1】:

random.randint() 是包容性的,所以如果你得到一个等于 HORSE_NUM 的随机整数,它就会越界。试试

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

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 2018-04-22
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2023-03-10
    相关资源
    最近更新 更多