【问题标题】:Getting a TypeError trying find the median of a list (python)获取 TypeError 尝试查找列表的中位数(python)
【发布时间】:2022-11-25 02:24:36
【问题描述】:

我正在做一个编码挑战,我需要找到列表的最小值、最大值、平均值和中值并输出两个元组(其中一个是平方元组)。

除了中位数之外,我已经设法输出了正确的结果。我收到一个 TypeError: object of type 'NoneType' has no len()

def exercise3(l):
    l2 = [number ** 2 for number in l]    
    def median(l):
        l1 = l.copy().sort()
        if len(l1)%2 != 0:
            median = l1[len(l1)/2]
            return median
        else:
            mid = len(l1) // 2
            median = (l1[mid] + l1[~mid]) / 2
            return median
    def calcStats(l):
        minL = min(l)
        avgL = sum(l) / len(l)
        medL = median(l)
        maxL = max(l)
        return minL, avgL, medL, maxL
    
    return calcStats(l), calcStats(l2)

【问题讨论】:

    标签: python list statistics


    【解决方案1】:

    如果你的比赛规则不禁止使用 python 标准库,我会选择

    from statistics import median
    median(l)
    

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 2021-01-14
      • 1970-01-01
      • 2015-02-28
      • 2013-11-21
      • 2020-03-24
      相关资源
      最近更新 更多