我使用范围函数创建了一个列表变量(余额)
我的要求是从收入中减去费用并将产出放入余额变量中。
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 列出使用 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)
]