python中的索引外错误

2024-04-25 20:22:23 发布

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

有人能帮我为什么我要摆脱索引错误吗。你知道吗

def subset(lst,n):
A = 0
B = 1
C = 2
for i in range(len(lst)):
    if n == lst[A]+lst[B]+lst[C]:
        return ('True')
    if n != lst[A]+lst[B]+lst[C]:
        C = C+1

我的产量正在下降。你知道吗

subset([1,2,5,3],6)
Out[136]: 'True'
subset([1,2,5,3],9)
if n == lst[A]+lst[B]+lst[C]:

IndexError: list index out of range

我需要通过列表,加上三个数字,然后检查它是否等于n


Tags: intrueforlenreturnifdef错误
3条回答

您没有使用i,而是将C相加,这会导致错误。 也许以下就是你想要的:

def subset(lst,n):
    for A in range(len(lst)-2):
        for B in range(A+1, len(lst)-1):
            for C in range(B+1, len(lst)):
                if n == lst[A]+lst[B]+lst[C]:
                    return ('True')
    return('False')

C=C+1最终变为4,[1,2,5,3]的最后一个索引是3。 这就是为什么在n==lst[A]+lst[B]+lst[C]行中失败的原因

You may want to change you loop to:

 for i in range(len(lst)):
        if n == lst[A]+lst[B]+lst[C]:
            return True
        elif C < len(lst) -1:
            C += 1
       else:
            return False

你的台词

if n != lst[A]+lst[B]+lst[C]:
        C = C+1

正在允许C增长。在很多情况下,这段代码都会因为同样的原因失败,但是有一些特定的输入不会导致这段代码失败,所以它不会总是这样做。您需要确保C永远不会超过您的列表长度-1

我不完全确定你想做什么,所以这就是为什么你会得到索引外错误的直接答案。你知道吗

相关问题 更多 >