简体   繁体   English

使用reduce()在python中计算平均值

[英]calculate average in python using reduce()

Given an sequence of numbers, for example, seq = [2, 4, 2, 4] Then calculate its mean value using reduce and lambda in python. 给定一个数字序列,例如seq = [2,4,2,4],然后使用python中的reduce和lambda计算其平均值。 I've already know one solution: 我已经知道一种解决方案:

def my_mean(seq):
    return reduce(lambda x, y: x + y, seq) / float(len(seq))

And then another idea comes to me: 然后我想到另一个主意:

def my_mean(seq):
    return reduce(lambda x, y: (x * seq.index(y) + y) / float(seq.index(y) + 1))

But the second solution doesn't work. 但是第二种解决方案不起作用。 bad case: seq = [2, 4, 2] returns 2.0 while seq = [2, 2, 4] returns 3.0.In fact, the return values should be the same. 坏情况:seq = [2,4,2]返回2.0,而seq = [2,2,4]返回3.0。实际上,返回值应该相同。 Could you please give me some hints whats wrong with my second solution? 您能否给我一些提示,第二种解决方案出了什么问题? Thank you and sorry for my broken English. 谢谢,对不起,我的英语不好。

First of all, you're missing the second argument of reduce : seq . 首先,您缺少reduce的第二个参数: seq

The problem is, index will find the first entry. 问题是, index将找到第一个条目。 If you have duplicates, that will mess up the calculation. 如果重复,那将使计算混乱。

You can use enumerate to fix it, but it's simply not worth it.. 您可以使用enumerate进行修复,但这根本不值得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM