首页 > 解决方案 > 在 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) 但我不知道我将如何操纵它。

标签: pythonlistloopsiteration

解决方案


您的循环中没有检查索引是否超出范围,即检查 i 与列表“收益”中的项目数。试试这个方法:

earnings = [94500,65377,84524]
deductions = [20000,18000,19000]

tax = [] #empty list
i = -1    #iterative counter
while True:
    i=i+1
    if i >= len(earnings):
        break
    if (earnings[i] > 23000):
        tax.append(0.14*earnings[i])
        continue
print ('Tax calculation has been completed')
print ('Number of iterations: ',i)

推荐阅读