对象列表的属性

假设我有一个类 C,它有属性 a

从 Python 中的 C列表中获得 a之和的最佳方法是什么?


我试过以下代码,但我知道这不是正确的方法:

for c in c_list:
total += c.a
68045 次浏览

Use a generator expression:

sum(c.a for c in c_list)

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.

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])

Use built-in statistics module:

import statistics


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