范围函数不适用于执行减法

问题描述 投票:0回答:1

我使用范围函数创建了一个列表变量(余额)

我的要求是从收入中减去费用并将产出放入余额变量中。

earnings = [10, 20, 30, 24, 18]
expenses = [8, 14, 15, 20, 10]
balance = list(range(1, 6))

for i in balance:
   balance[i] = earnings[i] - expenses[i]    

输出:

IndexError 
Traceback (most recent call last)
Input In [96], in <cell line: 1>()
      1 for i in balance:
----> 2     balance[i] = earnings[i] - expenses[i]

IndexError: list index out of range

预期结果:

从收入中减去费用并将产出放入余额变量中。

python loops
1个回答
0
投票

Python 列出使用 https://en.wikipedia.org/wiki/Zero-based_numbering

有几种写法:

earnings = [10, 20, 30, 24, 18]
expenses = [8, 14, 15, 20, 10]

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

balance = []
for earning, expense in zip(earnings, expenses):
   balance.append(earning - expense)
earnings = [10, 20, 30, 24, 18]
expenses = [8, 14, 15, 20, 10]

balance = [
    earning - expense
    for earning, expense in zip(earnings, expenses)
]
© www.soinside.com 2019 - 2024. All rights reserved.