在 Python 中的 while 循环中附加列表会出现错误消息“列表索引超出范围”

所以我试图做一个简单的循环,由于某种原因,我似乎无法理解为什么会出现错误消息。


earnings = [94500,65377,84524]

deductions = [20000,18000,19000]


tax = [] #empty list

i = -1    #iterative counter

while True:

    i=i+1

    if (earnings[i] > 23000):

        tax.append(0.14*earnings[i])

        continue

    else:

        break

print ('Tax calculation has been completed')

print ('Number of iterations: ',i)

我觉得它与这条线有关, if (earnings[i] > 23000) 但我不知道我将如何操纵它。


扬帆大鱼
浏览 188回答 2
2回答

莫回无

您可以使用enumerate来迭代earnings列表,同时生成从以下位置开始的迭代计数器1:tax = []for i, earning in enumerate(earnings, 1):&nbsp; &nbsp; if earning <= 23000:&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; tax.append(0.14 * earning)print('Tax calculation has been completed')print('Number of iterations: ', i)

慕斯709654

您的循环中没有检查索引是否超出范围,即检查 i 与列表“收益”中的项目数。试试这个方法:earnings = [94500,65377,84524]deductions = [20000,18000,19000]tax = [] #empty listi = -1&nbsp; &nbsp; #iterative counterwhile True:&nbsp; &nbsp; i=i+1&nbsp; &nbsp; if i >= len(earnings):&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; if (earnings[i] > 23000):&nbsp; &nbsp; &nbsp; &nbsp; tax.append(0.14*earnings[i])&nbsp; &nbsp; &nbsp; &nbsp; continueprint ('Tax calculation has been completed')print ('Number of iterations: ',i)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python