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:
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:
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_prodsThis 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: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_prodsBut of course I lose the information about the unit of measure and I don't know how to add it.Thank you in advance
