如何解决如何存储每个类别对象的总提款金额?
我有一个Category
类,并且该类的每个实例都有一个分类帐属性。该分类帐属性实际上是词典的列表,其中包含取款和存款金额以及以{"amount" : amount,"description" : description}
形式的描述。现在,我想定义一个函数create_spend_chart
,该函数将对象列表作为参数,并找到提款的总额。我已经能够成功做到这一点:
def create_spend_chart(categories):
total_withdrawn = 0
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
但是我在这里面临的问题是,我似乎无法分别存储每个类别对象的总提款金额。我该怎么办?
我的代码库可能会帮助您ins回答问题:
class Category:
def __init__(self,name):
self.name = name
self.ledger = list()
def get_balance(self):
total_balance = 0
for i in self.ledger:
total_balance += i["amount"]
return total_balance
def check_funds(self,amount):
if self.get_balance() >= amount:
return True
else:
return False
def deposit(self,amount,description = "Deposit"):
form = {"amount" : int(amount),"description" : description}
self.ledger.append(form)
def withdraw(self,description = "Withdrawal"):
if description == None:
description = "Withdrawal"
form = {"amount" : -int(amount),"description" : description}
if self.check_funds(amount):
self.ledger.append(form)
return True
else:
return False
def transfer(self,category_object):
form1 = {"amount" : -int(amount),"description" : f"Transfer to {category_object.name}"}
form2 = {"amount" : int(amount),"description" : f"Transfer from {self.name}"}
if self.check_funds(amount):
self.ledger.append(form1)
category_object.ledger.append(form2)
return True
else:
return False
def __repr__(self):
Ledger = ""
for i in self.ledger:
if len(i["description"]) > 23:
des = i["description"][:23]
else:
des = i["description"]
Ledger += des.ljust(23) + str(round(i["amount"],2)).rjust(7) + "\n"
Ledger = Ledger + "Total: " + str(round(self.get_balance(),2))
receipt = f"{self.name}".center(30,"*") + "\n" + Ledger
return receipt
def create_spend_chart(categories):
total_withdrawn = 0
withdrawals = list()
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
解决方法
使用collections.defaultdict
来简化诸如馅饼之类的聚合。
import collections
# ...
withdrawn_per_category = collections.defaultdict(int)
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] += -p["amount"]
(我选择使用int
作为默认数据类型,但在这里并没有什么关系,只要它是可转换的数字类型即可。)
没有collections
如果由于某种原因您不想使用方便的内置collections
模块,则可以使用常规命令自己模拟相同的行为:
withdrawn_per_category = {}
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] = withdrawn_per_category.get(i.name,0) - p["amount"]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。