Python之中位数
2016-06-08 09:44
387 查看
给你一个list L, 如 L=[0,1,2,3,4], 输出L的中位数(若结果为小数,则保留一位小数)
#Python版本:2.7.10
#2.7中两个整数除法直接向下取整了,导致无法出现小数,所以我们导入了future 中的division模块<精确除法>
#list中有sort方法,进行排序,会修改原来的列表。默认从小到大,若要从大到小可以加入参数reverse=True,或者改变排序的方式cmp(自己定义)
#python中还内置了sorted()函数,可以对序列进行排序,但是不回对原来的序列进行修改,返回一个排序好的序列,也可以使用参数reverse=True,或者改变排序的方式进行排序,
#int()转化为整数并向下取整
#math.floor() 下舍整数,返回浮点数
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
相关文章推荐
- python & pandas链接mysql数据库
- 利用python进行数据分析-pandas入门2
- python安装ez_setup.py 【windows环境】
- Python while 循环使用实例
- Python数据类型转换
- python中的for循环如何控制步长
- python计算文件的行数和读取指定行的内容
- "Python" + "OpenCV" 环境配置
- python sqlalchemy 写数据
- [转]LIBSVM-3.18在python环境下的使用
- windows安装theano
- machine learning in action 之二 —— k-Nearest Neighbors
- Python入门笔记
- windows下python 安装igraph库报错 Cannot find the C core of igraph on this system using pkg-config.的解决
- python 列表解析
- python 多个迭代器 VS 单个迭代器
- python3.x dict 迭代
- Python3学习笔记02-程序文件改为脚本执行
- 廖雪锋笔记1---python变量类型
- python自学笔记