Python:列表中数字的中位数
当我在PyScripter上运行我的程序时,得到了预期的中位数4.5
。但是在Ideone或者codecademy上运行同样的代码却返回了4
。你知道为什么结果会不一样吗?谢谢。
#Create a function that returns the median of a list of numbers
def median(list_of_numbers):
#Make a copy of list_of_numbers and sort the new list
lst = list_of_numbers
lst = sorted(lst)
#Get the length of list and use it to index through the list
lst_length = len(lst)
index = int(lst_length/2)
#If length if even, average the two middle numbers
if lst_length%2==0:
a= lst[index-1]
b = lst[index]
result = (a+b)/2
#If length is odd, return the middle number
else:
result = lst[index]
return result
print (median([4, 5, 5, 4]))
我的PyScripter版本:* Python 3.3.5 (v3.3.5:62cf4e77f785, 2014年3月9日,10:37:12) [MSC v.1600 32位 (Intel)] 在win32上.*
2 个回答
0
import statistics as s
def mid(data):
return(int(s.median(data)))
middle = mid([3,4,6,3,12,6,45,32,78])
print(middle)
我会使用统计模块。如果你想要输出结果是整数或者小数,只需要转换一下类型(分别用float()或者int())。
1
在Python 2.x中,你需要把代码里出现的两个2
都换成2.
,这样才能确保进行浮点数的除法运算。
你提供的ideone链接是Python 2.x版本,看来你的codeacademy解释器也是这个版本。