python - 在 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)
但我不知道我将如何操纵它。
解决方案
您的循环中没有检查索引是否超出范围,即检查 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)
推荐阅读
- c# - 如何让我的异常输出为带有 NLOG 的结构化 JSON
- javascript - 如何在单个 Alpine.js 属性中执行多个语句?
- postgresql - 如何在 helm 图表中使用 postgres-exporter 的 --extend.query-path 参数?
- html - 如何更改小盒子内容的行?
- php - MySQL WHERE 过滤器基于 SELECT 中的子查询
- php - 水平显示每周数据
- javascript - 为什么我的克隆数组的代码不起作用 JavaScript
- jupyter-notebook - 为什么在 jupyter notebook 中找不到该文件?
- python - Discord.py Bot 响应时间过长
- python - 破折号回调依赖于先前回调中的先前计算和 # 参数的 TypeError