Python中的修剪平均值
我试图用python中的手动函数计算列表的修剪平均值,但我不知道如何调整公式 我希望您可以为函数提供一个alpha参数,例如0.1(减少10%的异常值) 到目前为止我的代码(本例中0.1是alpha值): alpha=0.1的平均值应该是21,但我不知道我需要如何调整代码 谢谢Python中的修剪平均值,python,statistics,mean,Python,Statistics,Mean,我试图用python中的手动函数计算列表的修剪平均值,但我不知道如何调整公式 我希望您可以为函数提供一个alpha参数,例如0.1(减少10%的异常值) 到目前为止我的代码(本例中0.1是alpha值): alpha=0.1的平均值应该是21,但我不知道我需要如何调整代码 谢谢 lst = [5,30,29,15,25,5,13,28,24,29] def tmean(lst, alpha): s = sorted(lst) # Caclculate number of ele
lst = [5,30,29,15,25,5,13,28,24,29]
def tmean(lst, alpha):
s = sorted(lst)
# Caclculate number of elements to trim from the beginning and end
a = round(alpha * len(lst)
# Check if alpha can actually remove any elements and if not return straight mean
if a == 0:
return sum(lst) / len(lst)
# Remove trimmed elements from the list
trimmed_list = s[a:-a]
# Check if there is a list left after trimming
if len(trimmed_list) == 0:
return
# Calculate average on the new list
trimmed_ave = sum(trimmed_list)/len(trimmed_list)
print(trimmed_ave)
return trimmed_ave
tmean(lst, 0.1)
显然,上面的一些阶段可以组合在一起,以获得更简洁的代码,但为了便于解释,它们被分成了几行。代码运行良好。正是我想要的。非常感谢。如果我有一个包含例如4个元素[1,10,20,85]和alpha=0.1的列表,那么代码不幸不起作用,因为在这种情况下,a=0,而修剪后的列表将因为-a而为空。有什么建议吗?谢谢。您可以添加一个检查,看看列表是否足够长,是否可以按照给定的alpha值进行修剪,如果不够长,只需返回直接平均值(已编辑原始答案)
lst = [5,30,29,15,25,5,13,28,24,29]
def tmean(lst, alpha):
s = sorted(lst)
# Caclculate number of elements to trim from the beginning and end
a = round(alpha * len(lst)
# Check if alpha can actually remove any elements and if not return straight mean
if a == 0:
return sum(lst) / len(lst)
# Remove trimmed elements from the list
trimmed_list = s[a:-a]
# Check if there is a list left after trimming
if len(trimmed_list) == 0:
return
# Calculate average on the new list
trimmed_ave = sum(trimmed_list)/len(trimmed_list)
print(trimmed_ave)
return trimmed_ave
tmean(lst, 0.1)