Quantcast
Channel: Finding the average of a list - Stack Overflow
Viewing all articles
Browse latest Browse all 26

Answer by SingleNegationElimination for Finding the average of a list

$
0
0

In order to use reduce for taking a running average, you'll need to track the total but also the total number of elements seen so far. since that's not a trivial element in the list, you'll also have to pass reduce an extra argument to fold into.

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]>>> running_average = reduce(lambda aggr, elem: (aggr[0] + elem, aggr[1]+1), l, (0.0,0))>>> running_average[0](181.0, 9)>>> running_average[0]/running_average[1]20.111111111111111

Viewing all articles
Browse latest Browse all 26

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>