【问题标题】:Adding the items in a list within a list to find the average在列表中添加列表中的项目以查找平均值
【发布时间】:2015-01-20 20:24:44
【问题描述】:

好的,所以我在一个列表中有一个列表(像疯狂一样开始),它看起来像这样......

list = [[62.0, 0.07427184466019418, 9, 0.6058252427184466, 0.07455501618122977, 0.0634304207119741, 0.12637540453074433, 0.4357200647249191, 0, 0, 45], [98.0, 0.32406580793266165, 16, 1.9099604642265018, 0.5279938783318454, 0.19997449304935594, 3.547506695574544, 1.3736768269353399, 0, 0, 35]]

我要做的是找到每个项目的平均值。 因此,在上面的列表中,我将添加 62.0 + 98.0(62 + 98 是每个列表中的第一项)并除以 2 以找到平均值。

我在想这样的事情......

for row in list:

        counter = + 1
        row[0] = row[0] + row[0] / under_total

非常欢迎任何建议。我希望这是有道理的,谢谢你的关注。

【问题讨论】:

    标签: python list loops for-loop


    【解决方案1】:
    L = [[62.0, 0.07427184466019418, 9, 0.6058252427184466, 0.07455501618122977, 0.0634304207119741, 0.12637540453074433, 0.4357200647249191, 0, 0, 45], [98.0, 0.32406580793266165, 16, 1.9099604642265018, 0.5279938783318454, 0.19997449304935594, 3.547506695574544, 1.3736768269353399, 0, 0, 35]]
    
    answer = []
    for col in zip(*L):
        answer.append(sum(col)/len(col))
    print(answer)
    

    输出:

    [80.0, 0.1991688262964279, 12.5, 1.2578928534724743, 0.30127444725653757, 0.131702456880665, 1.8369410500526442, 0.9046984458301295, 0.0, 0.0, 40.0]
    

    如果您的列表中有非数字条目:

    answer = []
    for col in zip(*L):
        col = [c for c in col if isinstance(c, int) or isinstance(c, float)]
        answer.append(sum(col)/len(col))
    print(answer)
    

    如果确实有可能有一列充满非数字值,那么您可能会遇到 ZerDivisionError。因此,假设在这些情况下,您想说平均值为0。那么这应该可以解决问题:

    answer = []
    for col in zip(*L):
        col = [c for c in col if isinstance(c, int) or isinstance(c, float)]
        if col:
            answer.append(sum(col)/len(col))
        else:
            answer.append(0)
    print(answer)
    

    【讨论】:

    • 您好,谢谢您的回答。如果列表中有两项不是数字,您知道该怎么做吗?你会怎么滑倒这些?我的列表如此
    • @DerekMcAuley:查看编辑。这应该处理任何非数字条目
    • 谢谢,但我收到“ZeroDivisionError:除以零”错误
    【解决方案2】:

    内置zip 功能适用于这项工作:

    >>> s
    [[62.0, 0.07427184466019418, 9, 0.6058252427184466, 0.07455501618122977, 0.0634304207119741, 0.12637540453074433, 0.4357200647249191, 0, 0, 45], [98.0, 0.32406580793266165, 16, 1.9099604642265018, 0.5279938783318454, 0.19997449304935594, 3.547506695574544, 1.3736768269353399, 0, 0, 35]]
    >>> [(i + j) / 2 for i, j in zip(s[0], s[1])]
    [80.0, 0.1991688262964279, ...]
    

    我们甚至可以将其推广到任意数量的子列表:

    >>> [sum(l)/len(l) for l in zip(*s)]
    [80.0, 0.1991688262964279, 12, 1.2578928534724743, 0.30127444725653757, 0.131702456880665, 1.8369410500526442, 0.9046984458301295, 0, 0, 40]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      相关资源
      最近更新 更多