好吧,我有一个列表中的列表(像疯狂一样的开始),它看起来像这样......
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/