[英]Why is the code below return an empty list.I could not understand the reason of it so if someone can help me about that , that will make me happy
def outlier(*args):
outlist=[]
def median(args1):
if(len(args1)%2==1):
return list(sorted(args1))[int((len(args1)/2)-0.5)]
else:
return (list(sorted(args1))[int(len(args1)/2)]+list(sorted(args1))[int(len(args1)/2)-1])/2
def fmax(args2):
sortargs=sorted(args2)
return sortargs[-1]
def fmin(args3):
sortargs=sorted(args3)
return sortargs[0]
q1=median(list(range(fmin(args),floor(median(args))+1)))
q3=median(list(range(floor(median(args)),fmax(args)+1)))
for i in args:
if(i<(q1-1.5*(q3-q1)) or i>(q3+1.5*(q3-q1)*(q3-q1))):
outlist.append(i)
return outlist
print(outlier(1,2,3,4,5,6,7,8,9,10,100000000))
I have tried to get the outlier values of a list in Python, but everytime I try it,it returns an empty list or throws an error, but I want neither of these so if you are able to solve my problem and solve, that will make me happy.Thanks for reading if you need more information to solve the problem, you may ask.我试图在 Python 中获取列表的异常值,但每次我尝试它时,它都会返回一个空列表或引发错误,但我不想要这些,所以如果你能够解决我的问题并解决,那将让我开心。感谢阅读如果您需要更多信息来解决问题,您可以询问。
If the list returns empty, the reason is that neither parts of your if
condition is met and so nothing is appended to the list:如果列表返回空,原因是您的
if
条件的任何部分都不满足,因此列表中没有附加任何内容:
if(i<(q1-1.5*(q3-q1)) or i>(q3+1.5*(q3-q1)*(q3-q1))): # never met
Why is that so?为什么呢? Well -
q1
and q3
are calculated here:那么 -
q1
和q3
在这里计算:
q1 = median(list(range(fmin(args),floor(median(args))+1))) q3 = median(list(range(floor(median(args)),fmax(args)+1)))
and both are range
s converted to list
s, stuffed into your median
function that returns list
s as well.并且两者都是
range
s 转换为list
s,填充到您的median
function 中,它也返回list
s。
q3-q1
(list - list) is?q3-q1
(list - list) 的结果是什么?1.5*(q3-q1)*(q3-q1)
(1.5 times the square of list-list) should be?1.5*(q3-q1)*(q3-q1)
(list-list 平方的 1.5 倍)的结果应该是多少? If you are not adverse to useing bigger module, you could calculate the quartiles using numpy, see如果您不反对使用更大的模块,您可以使用 numpy 计算四分位数,请参阅
or use this answer that gives you a function for manual calculation:或使用此答案为您提供 function 进行手动计算:
BTW:顺便提一句:
sorted()
returns a list so list(sorted(..))
is redundant sorted()
返回一个列表,因此list(sorted(..))
是多余的def minmax(data):
if len(data) < 2:
raise ValueError("Must be iterable of len 2 or more")
srt = sorted(data)
return srt[0],srt[-1]
instead of代替
def fmax(args2): sortargs=sorted(args2) return sortargs[-1]
def fmin(args3): sortargs=sorted(args3) return sortargs[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.