【问题标题】:calculate mean and min of lists with None types included计算包含 None 类型的列表的平均值和最小值
【发布时间】:2019-08-12 23:49:51
【问题描述】:

我必须计算以下列表的平均值:

j=[20, 30, 40, None, 50]

还有这些嵌套列表中的最小值,其中也包括相同的值:

x = [[20, 30, 40, None, 50], [12, 31, 43, None, 51]]

应该返回[12,30,40,50],但以下代码不起作用。

print(list(map(min, zip(*x))))
TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

平均而言,我尝试了这个:

import statistics
statistics.harmonic_mean(j)

他们都没有处理过这种类型的列表。

【问题讨论】:

    标签: python python-3.x list mean min


    【解决方案1】:

    您可以过滤掉“无”值以获得平均值和分钟数。例如:

    from statistics import mean
    
    data = [[20, 30, 40, None, 50], [12, 31, 43, None, 51]]
    
    mean_val = mean(d for d in data[0] if d is not None)
    print(mean_val)
    # 35
    
    min_vals = [min(a, b) for a, b in zip(*data) if a is not None and b is not None]
    print(min_vals)
    # [12, 30, 40, 50]
    

    【讨论】:

    • 条件错误if d 对于零也是错误的,但它们是完全有效的数字。正确的是mean_val = mean(d for d in data[0] if d is not None)
    猜你喜欢
    • 2020-06-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多