python中怎么对列表以区间进行统计?
问题描述
python中怎么对列表以区间进行统计?假设list=[1,1,1,2,3,4,4,5,5,6,7,7,7,7,8,9,9,9,10……99,99,99,100,100]
怎么写程序可以以10为一个区间分别统计,如统计出小于10的数字频率,大于10小于20的频率,大于20小于30的频率……大于90小于100的频率?抱歉题目描述的不好
问题解答
回答1:# code for python3from itertools import groupbylst = [1, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7, 7, 8, 9, 9, 9, 10, 99, 99, 99, 100, 100]dic = {}for k, g in groupby(lst, key=lambda x: (x-1)//10): dic[’{}-{}’.format(k*10+1, (k+1)*10)] = len(list(g)) print(dic)
結果:
{’91-100’: 5, ’1-10’: 19}
我回答過的問題: Python-QA
回答2:# coding: utf-8lst = [1, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7, 7, 8, 9, 9, 9, 10, 99, 99, 99, 100, 100]intervals = {’{0}-{1}’.format(10 * x + 1, 10 * (x + 1)): 0 for x in range(10)}for _ in lst: for interval in intervals:start, end = tuple(interval.split(’-’))if int(start) <= _ <= int(end): intervals[interval] += 1print intervals
相关文章:
1. html - 移动端radio无法选中2. javascript - 我的站点貌似被别人克隆了, google 搜索特定文章,除了域名不一样,其他的都一样,如何解决?3. [python2]local variable referenced before assignment问题4. php - 微信开发验证服务器有效性5. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?6. Python2中code.co_kwonlyargcount的等效写法7. javascript - 求帮助 , ATOM不显示界面!!!!8. javascript - vue+iview upload传参失败 跨域问题后台已经解决 仍然报403,这是怎么回事啊?9. javascript - [MUI 子webview定位]10. mysql - 请问数据库字段为年月日,传进的参数为月,怎么查询那个月所对应的数据
