python - 将列表中的项目添加到列表中以查找平均值

标签 python list loops for-loop

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

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 是每个列表中的第一项)并除以二来找到平均值。

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

for row in list:

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

非常欢迎任何建议。我希望这是有道理的,感谢您的浏览。

最佳答案

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)

关于python - 将列表中的项目添加到列表中以查找平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27082564/

相关文章:

Python .extend 不必要地拆分字符

python - 输入二维矩阵的每个元素的最短方法

具有可绘制 int 数组的 Android ListView 可提高性能

c# - 列表中的碰撞检测

java - 通过DatagramSocket发送列表?

c# - foreach 或 Repeater - 哪个更好?

python - 使用 Python 和 Selenium 进行网页抓取,不知道如何获取动态数据

python - pandas - 与 matplotlib 进行绘图集成

python - 正则表达式 Python 错误

Javascript 如果为空则从数组中移除