我的代码的目的是在列表列表中找到平均值和方差。约束是:如果在“linesort”中有两个或更多列表,其中前两个元素相等,则计算添加列表的第三个元素的平均值。我的问题是包括方差和平均值的计算,并返回一个包含 [a, b, mean,variance] 的列表。非常感谢你。
linesort = [[1, 2, 3.00], [1, 2, 5.00], [1, 4, 7.00], [1, 4, 3.00] ,[3, 6, 5.2]]
new = []
final = []
count=0
for el in linesort:
new.append(el[:-1])
tnew = [tuple(t) for t in new]
setnew = set(tnew)
setnew = [list(t) for t in setnew]
for items in setnew:
inds = [i for i,x in enumerate(new) if x == items]
if len(inds) > 1:
somma = 0
for ind in inds:
print(somma)
somma = linesort[ind][2] + somma
media = somma/len(inds)
items.append(media)
final.append(items)
print(final)
期望输出:
('Output: ', [[1, 2, 4.0,1.0], [1, 4, 5.0,4.0]])
至于差异,我想过这行代码,但我无法让它工作。
variance = float(sum((linesort[ind][2] - media) ** 2 for linesort[ind][2] in linesort) / len(linesort))
哆啦的时光机
相关分类