Python错误代码:IndexError:索引错误列表索引超出范围 [英] Python Error code: IndexError: index error list index out of range

查看:1746
本文介绍了Python错误代码:IndexError:索引错误列表索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Python编写一个模拟赛马的函数。虽然没有赢家,但它会清除屏幕,显示马匹列表(所有马匹的索引都从零开始)。然后,在我标记的行上,代码混乱了。
我得到索引错误列表超出范围。我试图随机选择一匹马(随机选择一个索引号)并将值加1。但我似乎无法弄明白!!

I'm trying to write a function in Python that simulates a horse race. While there's no winner, it clears the screen, shows the list of horses (all have index starting at zero). Then, on the line I've marked, the code messes up. I get the index error list out of range. I'm trying to randomly pick a horse (randomly pick an index number) and add 1 to the value. But I can't seem to figure it out!!

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


推荐答案

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

random.randint() is inclusive, so if you get a random integer that is equal to HORSE_NUM it will be out of bounds. try

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

这篇关于Python错误代码:IndexError:索引错误列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆