简体   繁体   中英

Sum / Average an attribute of a list of objects

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

使用生成器表达式

sum(c.a for c in c_list)

If you are looking for other measures than sum, eg 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])

I had a similar task, but mine involved summing a time duration as your attribute ca . 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.

Use built-in statistics module:

import statistics

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM