Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python &引用;列表索引超出范围“;关于简单随机环_Python_Python 3.x_Loops_Random - Fatal编程技术网

Python &引用;列表索引超出范围“;关于简单随机环

Python &引用;列表索引超出范围“;关于简单随机环,python,python-3.x,loops,random,Python,Python 3.x,Loops,Random,我输入了这个简单的while循环,但由于某些原因,它有时会给我列表索引超出范围的错误。奇怪的是,它只是有时给我错误,我加的“骰子”越多,出错的可能性就越大。它出现在Dice\u total=Dice\u 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:

我输入了这个简单的while循环,但由于某些原因,它有时会给我列表索引超出范围的错误。奇怪的是,它只是有时给我错误,我加的“骰子”越多,出错的可能性就越大。它出现在
Dice\u total=Dice\u 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)

列表索引是基于零的,因此您需要选择一个介于0和5(包括)之间的随机值,而不是1和6:

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

您的问题是列表使用零索引<代码>骰子[1]返回列表中的第二项,而不是第一项。因此,
Dice[6]
将尝试访问不存在的第7项

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



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

我不明白的是,为什么要费心定义骰子呢?如果你更新了线路

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


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

Dice[6]
不存在。为什么你要使用一个列表,而直接使用
random.randint(1,6)
获得正确的输出,而不使用这些值作为索引?这很奇怪。我发现它非常困难,以前无法解决,现在我看得很清楚。甚至在我读答案之前。thxOr只需使用
Dice\u Total=Dice\u Total+random.randint(1,6)
Dice_Total = Dice_Total + (Dice[random.randint(0,5)])
Dice_Total = Dice_Total + random.randint(1,6)