[英]Mode function (python)
我试着写模式function:
C=[13, 15, 16, 19, 20, 20]
def mode(x):
y={}
for a in x:
if not a in y:
y[a]=1
else:
y[a]+=1
return [g for g,l in y.items() if l==max(y.values())]
print("The mode of List is", mod(C))
但是 output 是 13。代码有什么问题?
缩进问题,应该在完成 for 循环后返回:
def mode(x):
y={}
for a in x:
if not a in y:
y[a]=1
else:
y[a]+=1
return [g for g,l in y.items() if l==max(y.values())]
print("The mode of List is", mode(C))
只是为了补全,统计库中有 function 模式:
import statistics
C=[13, 15, 16, 19, 20, 20]
statistics.mode(C)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.