我想简化下面的代码:
def function(data):
ss, s, n = reduce(lambda a, b: map(sum, zip(a,b)), [(x*x, x, 1) for x in data])
return (ss - s*s/n) / n
到目前为止,我已经发现ss,s和n是数据中平方项的总和,数据中术语的总和,以及数据中术语的数量。知道了这一点,我将返回声明简化为(平方术语的平均值) - (平均平方)。有没有更好的方法来简化代码并获得相同的输出?提前致谢
答案 0 :(得分:0)
上述代码的初学者友好实现将是
def function(data):
#get sum of squares
sum_of_squares = sum(i*i for i in data)
#get sum
sum_of_items = sum(data)
#total elements
total_elements = len(data)
#same func