对每个输入中的值求和
我试图获取存储在字典中的每个变量的总值。我是一个初学者,正在为这行代码而苦苦挣扎。有人可以帮我找出这个错误吗?
income_list = {
"Job": [],
"Business": [],
"Dividends": [],
"Sideline": [],
"Others": []
}
total_income = 0
job = income_list["Job"].append(float(input(f"Enter income for job: € ")))
business = income_list["Business"].append(float(input(f"Enter income for Business: € ")))
dividends = income_list["Dividends"].append(float(input(f"Enter income for Dividends: € ")))
sideline = income_list["Sideline"].append(float(input(f"Enter income for Sideline: € ")))
others = income_list["Others"].append(float(input(f"Enter other incomes: € ")))
for value in income_list.values():
print(sum(value))
I am trying to get the total value of each variable that's stored in the dictionary. I am a beginner who's struggling with this line of code. Can someone help me figure out the bug?
income_list = {
"Job": [],
"Business": [],
"Dividends": [],
"Sideline": [],
"Others": []
}
total_income = 0
job = income_list["Job"].append(float(input(f"Enter income for job: € ")))
business = income_list["Business"].append(float(input(f"Enter income for Business: € ")))
dividends = income_list["Dividends"].append(float(input(f"Enter income for Dividends: € ")))
sideline = income_list["Sideline"].append(float(input(f"Enter income for Sideline: € ")))
others = income_list["Others"].append(float(input(f"Enter other incomes: € ")))
for value in income_list.values():
print(sum(value))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要总和,您可以使用列表理解:
即使您的收入来源包含多个值(因为它们是列表),此方法也将起作用。
通过为
sum
提供生成器可以实现相同的结果:You can use a list comprehension, given that you need a sum of sums:
This method will work even if your income sources contain multiple values (since they are lists).
The same result can be achieved by giving a generator to
sum
:你可以尝试这样的事情:
you could try something like this :
我认为你想要以下两件事之一:1)带有字典/对象的列表,或2)带有列表的字典。我会选择 1),因为它对我来说更直观,但由于您似乎已经在尝试实现 2),所以我也会这样做。
我将提供一个简约的示例,然后您应该能够将其扩展到您的程序。
I think you want one of two things: 1) a list with dictionaries/objects, or 2) a dictionary with lists. I would go with 1) because it feels more intuitive to me, but since it seems you are already trying to achieve 2), I will do that as well.
I will provide a mimimalistic example, and then you should be able to extend it to your program.
首先,如果您要存储的是单个值,则使用列表作为字典值是没有意义的。其次,您需要在 for 循环中添加“total_venue”变量。
该代码有效:
也就是说,我认为您甚至不需要为此使用字典,只需简单的浮点变量即可。
First, it makes no sense to use a list as the dictionary value if what you want to store is a single value. Second, you need to add to the "total_income" variable in the for loop.
That code works:
That said, I think you don't even need to use a dictionary for that, just simple float variables.