我不明白我的列表索引怎么会超出范围

2024-10-02 00:33:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

Tags: 代码fordef情况random计数sumprint
1条回答
网友
1楼 · 发布于 2024-10-02 00:33:41

基本上你错了的是你的循环是从1开始的,你的count{}是从0开始的,所以当你计算percentage_2时,它是从index 1开始的,例如:percentage_2 = (count[1] / freq)*100,它跳过了你的0th index,当你到达j=11时,就有一个index rangecount[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()

Output

相关问题 更多 >

    热门问题