简体   繁体   中英

average of attribute in a list of objects

I have a list of user's. Each user will have a waitTime attribute. How do I get the average waitTime for all users in the list? 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(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.

Using a generator expression and sum for the 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.

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