我不明白我的列表索引为何超出范围

I don't understand how my list index is out of range

j 在达到 5 时停止计数,尽管我的范围结束于 11。

为什么会这样,我该如何解决?

我的部分代码存在问题:

dice1 = random.randrange(1,7)

def probabilities_sum():
    print('\nprobability for 2 dices:')
    for j in range(1, 12):
        percentage_2 = (count[j] / freq) * 100
        procent_2 = str(percentage_2)
        print('this is J', j)
        print(j + 1, ':', procent_2)

基本上你错了,你的循环是从 1 开始的,而你的 count index 是从 0 开始的,所以当你计算 percentage_2 所以它是从 index 1 开始的,例如:percentage_2 = (count[1] / freq)*100,它跳过了你的 0th index,当你到达 j=11 时,所以有一个 index range count0-10count[11] 没有任何价值,这就是为什么有 index out of range error.

import random
count = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dice1 = random.randrange(1,7)
freq = 12
def probabilities_sum():
    print('\nprobability for 2 dices:')
    for j in range(1, 12):
        percentage_2 = (count[j - 1] / freq) * 100
        procent_2 = str(percentage_2)
        print('this is J', j)
        print(j + 1, ':', procent_2)

probabilities_sum()