在Python中,在while循环中追加列表会显示错误消息';列表索引超出范围';
所以我试着做一个简单的循环,出于某种原因,我似乎无法理解为什么会出现错误消息在Python中,在while循环中追加列表会显示错误消息';列表索引超出范围';,python,list,loops,iteration,Python,List,Loops,Iteration,所以我试着做一个简单的循环,出于某种原因,我似乎无法理解为什么会出现错误消息 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])
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)
但我不知道如何处理这个问题。您的循环中没有检查索引是否超出范围的检查,即检查i与列表“earnings”中的项目数。试着这样做:
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)
您可以使用
枚举
在收益
列表上迭代,同时从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)
tax=[]
对于i,枚举中的收入(收入,1):
如果您最初应该获得i=0,那么您的循环中没有检查索引是否超出范围的检查,即根据列表“收益”中的项目数检查i。Hi@Snuffles。在这种情况下,如果I=0,那么它将错过列表的第一个元素,因为计数器操作发生在if语句操作之前。即使我将其更改为零,错误“列表索引超出范围”仍然会出现。@san-由于我对Python非常陌生,我想知道您能否告诉我如何将其合并到我的代码中?@Crumbo0,我刚刚发布了答案。如果有帮助,请随意接受并投票。:-)