循环输出列表索引超出范围

时间:2018-04-08 18:47:40

标签: python

我被要求编写一个代码(在Spyder的Python 3.6上),它从左到右对列表“权重”的索引求和,并确定k的值,即可以添加的最大权重数。权重之和不得超过THRESHOLD值。

这是我到目前为止所提出的。

THRESHOLD = 30
weights = [4, 7, 3, 5, 6, 2, 3]
accumulative_weights = 0
k = 0

while accumulative_weights <= THRESHOLD:
    accumulative_weights = weights[k] + weights[k+1]
    k += 1

然而,它输出IndexError: list index out of range。任何想法为什么会发生这种情况?

2 个答案:

答案 0 :(得分:0)

您没有测试情况(在这种情况下发生的情况),在数组中的元素用尽之前,您永远不会发现超过阈值的权重总和。将您的代码修改为:

THRESHOLD = 30
weights = [4, 7, 3, 5, 6, 2, 3]
accumulative_weights = 0
k = 0

while k < len(weights)-1 and accumulative_weights <= THRESHOLD:
    accumulative_weights += weights[k] + weights[k+1]
    k += 1

答案 1 :(得分:0)

这可能是由标签和空格的混合造成的。 你可以尝试

THRESHOLD = 30
weights = [4, 7, 3, 5, 6, 2, 3]
accumulative_weights = 0
k = 0


while accumulative_weights < THRESHOLD:
        accumulative_weights = weights[k]+weights[k+1]
        k=k+1

但之后你会得到另一个循环错误,因为镜头重量7和你有THRESHOLD 30