azalea says

Python计算中位数和众数

一些代码:

def median(numbers): '''Return the median of the list of numbers.''' # Sort the list of numbers and take the middle element. n = len(numbers) copy = numbers[:] # So that "numbers" keeps its original order copy.sort() if n & 1: # There is an odd number of elements return copy[n / 2] else: return (copy[n / 2 - 1] + copy[n / 2]) / 2 def mode(numbers): '''Return the mode of the list of numbers.''' #Find the value that occurs the most frequently in a data set freq={} for i in range(len(numbers)): try: freq[numbers[i]] += 1 except KeyError: freq[numbers[i]] = 1 max = 0 mode = None for k, v in freq.iteritems(): if v > max: max = v mode = k return mode

同样的事用python stats module也可以做,对应的函数就是stats.median()和stats.mode(),但是我用stats.median()结果很奇怪,输入是一堆整数的list,结果median是小数。。希望高手告诉我这是为啥。。stats.mode返回一个list,第一个元素是众数的频度,第二个元素是所有众数的list(因为未必唯一),而上面的代码仅返回其中一个众数,当然简单改进一下就和stats.mode()完全一样啦

Reference: http://mail.python.org/pipermail/python-list/2004-December/294990.html

programming python 统计 · Tweet Edit