【发布时间】: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
【问题讨论】:
-
randints 上限是包容性的,因此您需要使用 -1,但列表索引也从 0 开始,因此您可能还想使用 `random.randint(0, HORSE_NUM -1)` 来允许索引 0 处的马被挑选。 docs.python.org/2/library/random.html#random.randint