【问题标题】:IndexError in Python codePython代码中的IndexError
【发布时间】:2015-02-17 19:06:42
【问题描述】:

我的代码应该评估背包问题的解决方案。 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!")

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

【问题讨论】:

    标签: list python-3.x indexing


    【解决方案1】:

    根据您的代码,我假设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。

    【讨论】:

    • 谢谢你~! :) 那太简单了,我不敢相信我错过了。 ://
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2020-06-19
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多