应用于 Python 中的列表的楼层除法运算符

Floor divison operator applied to a list in Python

def median(numbers):
    numbers.sort() 
    if len(numbers) % 2:
        # if the list has an odd number of elements,
        # the median is the middle element
        middle_index = int(len(numbers)/2)
        return numbers[middle_index]
    else:
        # if the list has an even number of elements,
        # the median is the average of the middle two elements
        right_of_middle = len(numbers)//2 
        left_of_middle = right_of_middle - 1
        return (numbers[right_of_middle] + numbers[left_of_middle])/2

结果示例:

>>> x=[5,10,15,20]
>>> median(x)
12.5
>>> x=[17,4,6,12]
>>> median(x)
9.0
>>> x=[13,6,8,14]
>>> median(x)
10.5

我有运行这个功能,而且工作正常。结果一开始看不懂,终于搞定了!

但是,我不明白为什么只有第一个结果符合预期。我的意思是结果是列表中间两个数字的平均值。

我希望你明白我是在自学,有时这并不容易。

您的函数仅适用于第一个示例,因为仅对第一个列表进行了排序。对其他列表进行排序或在函数内进行排序。

仅仅因为那一行:

numbers.sort() 

所以,[17,4,6,12]变成了[4,6,12,17],他的中位数是9

您可能会问:

Why is the median different from the mean?

那么答案是这样的:

The median is the value separating the higher half of a data sample, a population, or a probability distribution, from the lower half.

(来自 Wikipedia。)

For a data set, the terms arithmetic mean, mathematical expectation, and sometimes average are used synonymously to refer to a central value of a discrete set of numbers: specifically, the sum of the values divided by the number of values.

(来自 Wikipedia。)

这两个值可能相等,但一般来说是不同的:

如果你有 10 个穷人1 个百万富翁平均值 将是很高,但中位数(第六最穷人的工资)会仍然很低.