如何根据参数选择项,并在另一个函数中对其求和



嗨,我基本上有一个例子如何写一个程序来跟踪家庭收入和支出。所以我需要两个函数一个是向seznam中添加元素好的,我做到了。2个按参数选择项并求和的函数

如何在不出错的情况下添加第二个函数定义概述(月,年)并将从函数1到秒的每个类别仅按月和年求和

总是显示一些错误。

的结果应该是这样的print(概述(2022))打印{'food': 750, 'household': 150, 'housing': 300}

listof_items = {}
def add_item(day,month,year,amount,category):
listof_items ={day,month,year,amount,category}
print(listof_items )


add_item(15,10,2022,150,"food")
add_item(16,11,2022,250,"food")
add_item(17,11,2022,300,"housing")
add_item(18,11,2022,500,"food")
add_item(16,11,2022,150,"housing")

我试着把第二个函数,但这永远不会工作,我不知道如何从列表中获取项目,从函数1中只按月和年求和

尝试:

def add_item(lst, day, month, year, amount, category):
lst.append(
{
"day": day,
"month": month,
"year": year,
"amount": amount,
"category": category,
}
)

def overview(lst, month, year):
out = {}
for d in lst:
if d["month"] == month and d["year"] == year:
out.setdefault(d["category"], []).append(d["amount"])
return {k: sum(v) for k, v in out.items()}

listof_items = []
add_item(listof_items, 15, 10, 2022, 150, "food")
add_item(listof_items, 16, 11, 2022, 250, "food")
add_item(listof_items, 17, 11, 2022, 300, "housing")
add_item(listof_items, 18, 11, 2022, 500, "food")
add_item(listof_items, 16, 11, 2022, 150, "housing")
print(listof_items)

打印:

[
{"day": 15, "month": 10, "year": 2022, "amount": 150, "category": "food"},
{"day": 16, "month": 11, "year": 2022, "amount": 250, "category": "food"},
{
"day": 17,
"month": 11,
"year": 2022,
"amount": 300,
"category": "housing",
},
{"day": 18, "month": 11, "year": 2022, "amount": 500, "category": "food"},
{
"day": 16,
"month": 11,
"year": 2022,
"amount": 150,
"category": "housing",
},
]

:

print(overview(listof_items, 11, 2022))

打印:

{"food": 750, "housing": 450}

最新更新