【问题标题】:Floor divison operator applied to a list in Python地板除法运算符应用于 Python 中的列表
【发布时间】:2018-04-05 15:46:03
【问题描述】:
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

我已经运行了这个函数,它工作正常。一开始很难理解结果,但我终于明白了!。

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

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

【问题讨论】:

  • 我不明白你在这里问什么。结果在所有三种情况下都是正确的。

标签: python-3.x list function arithmetic-expressions floor-division


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    仅仅因为那一行:

    numbers.sort() 
    

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

    【讨论】:

      【解决方案3】:

      你可能会问:

      为什么中位数与平均值不同

      答案是这样的:

      中位数是将数据样本、总体或概率分布的上半部分与下半部分分开的值。

      (来自Wikipedia。)

      对于数据集,术语算术平均值、数学期望,有时甚至是平均值同义使用,指的是一组离散数字的中心值:具体而言,是值的总和除以值的数量。

      (来自Wikipedia。)

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

      如果你有 10 个穷人和一个 1 个百万富翁平均值非常高,但是中位数(第 6 个最穷的人的工资)将仍然非常低

      【讨论】:

        猜你喜欢
        • 2020-08-20
        • 1970-01-01
        • 2013-09-18
        • 1970-01-01
        • 2012-10-05
        • 2010-11-01
        • 2020-07-13
        • 2020-11-07
        • 2012-12-06
        相关资源
        最近更新 更多