[英]Sum / Average an attribute of a list of objects
Lets say I have class C
which has attribute a
.假设我有C
类,它具有属性a
。
What is the best way to get the sum of a
from a list of C
in Python?从 Python 中的C
列表中获取a
总和的最佳方法是什么?
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:如果您正在寻找除总和以外的其他度量,例如均值/标准差,您可以使用 NumPy 并执行以下操作:
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
.我有一个类似的任务,但我的任务涉及将持续时间总结为您的属性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.因为,如链接中所述, sum
需要一个起始值。
Use built-in statistics
module:使用内置statistics
模块:
import statistics
statistics.mean((o.val for o in my_objs))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.