Finding median of list in Python -
how find median of list in python? list can of size , numbers not guaranteed in particular order.
if list contains number of elements, function should return average of middle two.
here examples (sorted display purposes):
median([1]) == 1 median([1, 1]) == 1 median([1, 1, 2, 4]) == 1.5 median([0, 2, 5, 6, 8, 9, 9]) == 6 median([0, 0, 0, 0, 4, 4, 6, 8]) == 2
python 3.4 has statistics.median
:
return median (middle value) of numeric data.
when number of data points odd, return middle data point. when number of data points even, median interpolated taking average of 2 middle values:
>>> median([1, 3, 5]) 3 >>> median([1, 3, 5, 7]) 4.0
usage:
import statistics items = [1, 2, 3, 6, 8] statistics.median(items) #>>> 3
it's pretty careful types, too:
statistics.median(map(float, items)) #>>> 3.0 decimal import decimal statistics.median(map(decimal, items)) #>>> decimal('3')
Comments
Post a Comment