title: 给你一个list L, 如 L=[0,1,2,3,4], 输出L的中位数(若结果为小数,则保留一位小数)。
firstly , we shoule understand that what the meaning of the mid-number is ?
首先是要排序的,涉及到列表的排序sort方法的知识,直接是改变这个列表的
如果长度是奇数,那么就是中间位置的数值,如果是偶数,那么就是中间两个的均值(注意python中的index是从0开始的)
the key is that how we can to save the 小数点后面一位,这边利用round(数值,保留的位数)如果没有保留位数的参数那么默认保留0位
同时注意python中数值的转换,如果是整数和浮点型运算,默认转换为浮点型运算,只需要后面添加.0 如果是非复数和复数运算,那么默认转换为复数,添加0j。 如果是使用/ 整除 若整数和整数整除默认的答案就是整数,如果是有一个浮点数,那么结果也是浮点型的。
def out(a): if a%1==0: return a else: return round(a,1) L.sort() index =len(L) if index%2!=0: midIndex=( index-1)/2 print out(L[midIndex]) else: print out(float((L[int(index/2)-1]+L[int(index/2)]))/2)