Oct-21-2021, 09:38 PM
Hi,
I have a list of objects with certain attributes: I would like to group them and then calculate the sum of one of their attributes.
I'll try to explain better with an example:
This works fine, but I would like to calculate the sum using the relevant built-in function or in general to look for better ideas, I tried to write something like this:
But of course I lose the information about the unit of measure and I don't know how to add it.
Thank you in advance
I have a list of objects with certain attributes: I would like to group them and then calculate the sum of one of their attributes.
I'll try to explain better with an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
from itertools import groupby from dataclasses import dataclass @dataclass class Mine(): number: int material: str production: float um: str # Unit of measure activity: bool @dataclass class Total_Production(): material: str tot_production: float um: str # Unit of measure def by_material(p): return p.material def sum_by_material(mines): grouped_prods = [] for key, group in groupby( sorted (mines, key = by_material), by_material): tot = 0 for g in group: tot + = g.production grouped_prods.append(Total_Production(key, tot, g.um)) return grouped_prods |
1 2 3 4 5 6 |
def sum_by_material(mines): grouped_prods = [] for key, group in groupby( sorted (mines, key = by_material), by_material): tot = sum (g.production for g in group) grouped_prods.append(Total_Production(key, tot, ???)) return grouped_prods |
Thank you in advance