【问题标题】:"list index out of range" on simple random loop简单随机循环上的“列表索引超出范围”
【发布时间】:2018-01-09 17:20:54
【问题描述】:

我输入了这个简单的 while 循环,但由于某种原因,它有时会给我列表索引超出范围的错误。奇怪的是,它有时只会给我错误,而且我添加的“骰子”越多,出错的可能性就越大。它出现在Dice_total = Dice_Total + (dice[random.randint(1,6)])

import random

Dice = [1, 2, 3, 4, 5, 6]
Dice_Count = int(input())
Dice_Total = 0

while Dice_Count > 0:
    Dice_Total = Dice_Total + (Dice[random.randint(1,6)])
    print (Dice_Total)
    Dice_Count = Dice_Count - 1

print(Dice_Total)

【问题讨论】:

  • Dice[6] 不存在。
  • 你为什么要使用一个列表,当你通过使用random.randint(1, 6) 直接得到正确的输出,而不使用这些值作为索引?
  • 这很奇怪。我发现它非常困难,以前无法解决,现在我看得很清楚。甚至在我阅读答案之前。嗯,谢谢

标签: python python-3.x loops random


【解决方案1】:

正如其他人所说,问题是您调用的第 7 个索引 Dice[6] 超出了范围。 Python 上的索引基于 0,即Dice[0] 是第一项,Dice[5] 是第六项(最后一项)。

我不明白为什么还要定义 Dice?如果您更新了该行

Dice_Total = Dice_Total + (Dice[random.randint(0,5)])

Dice_Total = Dice_Total + random.randint(1,6)

会有同样的效果,而且你不会遇到这个问题。

【讨论】:

    【解决方案2】:

    列表索引是从零开始的,所以你需要选择一个介于 0 和 5(含)之间的随机值,而不是 1 和 6:

    Dice_Total = Dice_Total + (Dice[random.randint(0, 5)])
    

    【讨论】:

    • 或者直接使用Dice_Total = Dice_Total + random.randint(1, 6)
    【解决方案3】:

    您的问题是列表使用零索引。 Dice[1] 返回列表中的 2nd 项,而不是第一项。因此,Dice[6] 将尝试访问不存在的 7th 项。

    因此,您的random.randint(1, 6) 应该是random.randint(0, 5)


    import random
    
    Dice = [1, 2, 3, 4, 5, 6]
    Dice_Count = int(input())
    Dice_Total = 0
    
    while Dice_Count > 0:
        Dice_Total = Dice_Total + (Dice[random.randint(0,5)])
        print (Dice_Total)
        Dice_Count = Dice_Count - 1
    
    print(Dice_Total)
    

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2015-06-20
      • 2016-10-03
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      相关资源
      最近更新 更多