【问题标题】:Why is this out of range?为什么这超出范围?
【发布时间】:2022-08-10 21:19:49
【问题描述】:

考虑:

def generate_distribution(size, distribution_positive, distribution_negative):
    x = int(distribution_negative * 100)
    y = int(distribution_positive * 100)
    new_list = []
    i = 0
    for i in range(size):
        if i < x: # 0-24
            new_list[i-1].append(-1)
        elif i >= x and i < (x + y):
            new_list[i-1].append(1)
        else:
            new_list[i-1].append(0)
    return new_list

我是一个尝试学习 Python 的初学者。为什么这超出范围?

distribution_negative正向分布意味着以小数形式给出,因此上面乘以 100。

  • new_list 是空的,所以 new_list[i-1] 永远不会是有效的。也许您的意思是new_list.append(...) 而不是new_list[i-1].append(...)

标签: python list


【解决方案1】:

您名为new_list 的变量开始时为空,因此在第一次迭代中,您尝试访问new_list[i-1] 的位置,这意味着new_list[-1] 无效,因为列表当前为空。 在访问列表中的项目之前,您需要确保列表不为空。

另外,在确保列表不为空之后,请确保您没有访问负索引位置(也是无效的,除非您加入列表的一部分,即new_list[2: -1],它将为您提供从索引 2 到 1 的列表在最后一个之前)

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2016-08-22
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多