【问题标题】:I don't understand how my list index is out of range我不明白我的列表索引如何超出范围
【发布时间】:2020-09-02 18:11:37
【问题描述】:

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)

【问题讨论】:

  • 什么是count
  • count 计算 2 个骰子的总和(从 2 到 12)
  • 给出你写的代码。没有它就很难解决你的问题
  • count() 方法返回具有指定值的元素的数量,可以是任何类型(字符串、数字、列表、元组等)。要搜索的值。
  • 你能显示count()的代码吗?我认为这是问题的根源@Khan

标签: python list indexoutofboundsexception


【解决方案1】:

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

【讨论】:

  • 欢迎。请将此答案标记为您的解决方案。谢谢你.. :)
猜你喜欢
  • 2016-10-20
  • 2017-11-11
  • 1970-01-01
  • 2018-06-24
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
相关资源
最近更新 更多