Python 代码中的 IndexError

IndexError in Python code

我的代码应该评估背包问题的解决方案。 Wts 是一个列表。我会包括整个代码,但它真的很长。我遇到了这个问题:

totalwt += int(wts[i])
IndexError: list index out of range

但这是代码:

ev = input("Do you want to evaluate a potential solution? [y/n] ")
chosen = []
totalwt = 0
totalval = 0

if ev == 'y':
    print("Please enter a potential solution.")
    n = True
    while n == True:
        sol = int(input("Enter id [1..{0}] of item to be picked, or 0 when done. ".format(items)))
        if int(sol) >= 1 and int(sol) <= items:
            chosen.append(sol)
        else:
            n = False
    for i in chosen:
        totalwt += int(wts[i])
        totalval += int(vals[i])
    if totalwt < int(cap):
        print("Feasible: ","Total Wt = ",totalwt,"Total Val = ",totalval)
    else:
        print("Infeasible: ","Total Wt = ",totalwt,"Total Val = ",totalval)
elif ev == 'n':
    print("Okay. You are done. Thank you!")

我没有看到问题。但如果需要更多代码,我很乐意提供。

根据您的代码,我假设 items 是一个表示 wts 长度的整数。

如果是这样,您将需要更改此代码:

if int(sol) >= 1 and int(sol) <= items:
    chosen.append(sol)

对此:

if sol >= 1 and sol <= items:
    chosen.append(sol-1)

请注意,这是因为列表索引从 0 而不是 1 开始。