简体   繁体   中英

calculate average sum from second value of each tuple in python

I used this here to sum the second value of each tuple in a list: https://stackoverflow.com/a/12218119/9195816

sum(n for _, n in structure) works fine. But i dont need the sum, i only need the average. So something like sum(n for _, n in structure) \\ total_amount_of_values . But of course, this won't work:

TypeError: unsupported operand type(s) for /: 'float' and 'list'

My list looks ie like this: [1000, 900.84, 500, 1240.11]

n = [1000, 900.84, 500, 1240.11]
average = sum(n)/len(n)

This will give you the average of the list n


But it sounds like your list looks more like this

n = [(a,b), (c,d), ...]

and you want

b + d + ... / len(n)

If this is the case, then you can do this like so

average = sum(map(lambda x: x[1], n)) / len(n)

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