How to store the total withdrawal amount for each category object?

前端 未结 1 1398
生来不讨喜
生来不讨喜 2021-01-27 11:55

I have a Category class and there is a ledger attribute for each instance of this class. This ledger attribute is actually a list of dictionaries which contain the

相关标签:
1条回答
  • 2021-01-27 12:02

    Use a collections.defaultdict to make aggregations such as that easy as pie.

    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"]
    

    (I've opted to use int as the default data type, but it doesn't truly matter here, so long as it's a conversible numeric type.)

    Without collections

    If for some reason you don't want to use the handy, built-in collections module, you can emulate the same behavior yourself with a regular dict:

    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"]
    
    0 讨论(0)
提交回复
热议问题