好的,所以我在列表中有一个列表(像疯狂一样开始),它看起来像这样....
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
非常欢迎任何建议。我希望这是有道理的,谢谢你的期待。
答案 0 :(得分:2)
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)
答案 1 :(得分:1)
内置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]