在Python中,在while循环中附加列表会出现错误消息“List index out of range”

2024-09-30 01:23:39 发布

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

所以我试着做一个简单的循环,出于某种原因,我似乎不明白为什么会出现错误消息

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)但我不知道该如何处理这个问题


Tags: true消息if错误counterlistemptytax
2条回答

您可以使用enumerateearnings列表上迭代,同时生成从1开始的迭代计数器:

tax = []
for i, earning in enumerate(earnings, 1):
    if earning <= 23000:
        break
    tax.append(0.14 * earning)

print('Tax calculation has been completed')
print('Number of iterations: ', i)

在循环中没有检查索引是否超出范围的检查,即检查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)

相关问题 更多 >

    热门问题