Sum / Average an attribute of a list of objects

PythonListAttributesSum

Python Problem Overview


Lets say I have class C which has attribute a.

What is the best way to get the sum of a from a list of C in Python?


I've tried the following code, but I know that's not the right way to do it:

for c in c_list:
    total += c.a

Python Solutions


Solution 1 - Python

Solution 2 - Python

If you are looking for other measures than sum, e.g. mean/standard deviation, you can use NumPy and do:

mean = np.mean([c.a for c in c_list])
sd = np.std([c.a for c in c_list])

Solution 3 - Python

I had a similar task, but mine involved summing a time duration as your attribute c.a. Combining this with another question asked here, I came up with

sum((c.a for c in cList), timedelta())

Because, as mentioned in the link, sum needs a starting value.

Solution 4 - Python

Use built-in statistics module:

import statistics

statistics.mean((o.val for o in my_objs))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjsjView Question on Stackoverflow
Solution 1 - PythonphihagView Answer on Stackoverflow
Solution 2 - PythonHeribertView Answer on Stackoverflow
Solution 3 - PythonBill KiddView Answer on Stackoverflow
Solution 4 - PythonShital ShahView Answer on Stackoverflow