[英]average of attribute in a list of objects
I have a list of user's. 我有一个用户列表。 Each user will have a waitTime
attribute. 每个用户将具有一个waitTime
属性。 How do I get the average waitTime
for all users in the list? 如何获得列表中所有用户的平均waitTime
? The code below will probably work, but I'm guessing that there is a better way to do it. 下面的代码可能会起作用,但是我猜想有一种更好的方法。
sum = 0
for user in self.done:
sum += user.waitTime
sum/len(self.done)
You can use the builtin sum
function combined with a generator expression for this. 您可以为此使用内置sum
函数和生成器表达式。
sum(user.waitTime for user in self.done)/float(len(self.done))
The float
is only necessary in python2.x and only if all the user.waitTime
objects are integers. 仅在python2.x中并且仅在所有user.waitTime
对象都是整数时才需要float
。
Using a generator expression and sum
for the sum: 使用生成的表达和sum
为总和:
sum(user.waitTime for user in self.done) / float(len(self.done))
If the times are integers, you need to convert the result from len()
into float, otherwise you get integer division, ie truncating in Python 2. 如果时间是整数,则需要将len()
的结果转换为float,否则将得到整数除法,即在Python 2中被截断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.