给你一个list L, 如 L=[0,1,2,3,4], 输出L的中位数(若结果为小数,则保留一位小数)
from __future__ import division
def isFloat(s):
if isinstance(s, float):
print '%.1f' % s
else:
print s
L=[1,2,3.3333,4,5]
L.sort()
if len(L)%2==1:
isFloat(L[int(len(L)/2)])
else:
s=(L[int(len(L)/2)]+L[int(len(L)/2)-1])/2
isFloat(s)
#Python版本:2.7.10
#2.7中两个整数除法直接向下取整了,导致无法出现小数,所以我们导入了future 中的division模块<精确除法>
>>>from __future__ import division
>>> 5/2
2.5
>>>6/3
3.0
>>>5//2
2
#list中有sort方法,进行排序,会修改原来的列表。默认从小到大,若要从大到小可以加入参数reverse=True,或者改变排序的方式cmp(自己定义)
#python中还内置了sorted()函数,可以对序列进行排序,但是不回对原来的序列进行修改,返回一个排序好的序列,也可以使用参数reverse=True,或者改变排序的方式进行排序,
#int()转化为整数并向下取整
#math.floor() 下舍整数,返回浮点数
>>>import math
>>>floor(15.2)
15.0