You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用range创建列表执行收支减法时触发IndexError问题求助

问题分析与解决方案

错误原因

  1. 变量名拼写错误:代码中定义的earings应为earnings(属于输入笔误,若未修正后续还会触发未定义变量错误)
  2. 索引逻辑错误:balance = list(range(1,6))生成的列表是[1,2,3,4,5],循环时i取的是这些元素值。而Python列表索引从0开始,earnings和expenses的有效索引范围是0-4,当i=5时必然触发IndexError: list index out of range。

正确实现方式

方式1:用索引遍历(贴合你想用range的需求)

earnings = [10, 20, 30, 24, 18]
expenses = [8, 14, 15, 20, 10]
# 以收入列表长度为基准,创建初始balance(元素为0到4的索引值)
balance = list(range(len(earnings)))

# 遍历有效索引范围,逐个计算收支差
for i in range(len(earnings)):
    balance[i] = earnings[i] - expenses[i]

方式2:列表推导式(更简洁)

无需提前初始化balance,直接通过推导式生成结果:

earnings = [10, 20, 30, 24, 18]
expenses = [8, 14, 15, 20, 10]
balance = [earnings[i] - expenses[i] for i in range(len(earnings))]

方式3:用zip配对元素(最Pythonic)

zip会自动将两个列表的对应元素配对,无需手动处理索引:

earnings = [10, 20, 30, 24, 18]
expenses = [8, 14, 15, 20, 10]
balance = [income - cost for income, cost in zip(earnings, expenses)]

以上三种方式最终都会得到正确结果:[2, 6, 15, 4, 8]

内容的提问来源于stack exchange,提问作者Pavan Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 09:23:15