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. python3.x - python多进程,不能在同一窗口吗2. 如何解决tp6在zend中无代码提示3. python - 怎样在linux下开发flask web应用时查看代码出错(traceback)的地方。4. mysql - SQL添加记录的数据来源于同一个表5. php - 两个表数据怎么插到一个模板中,并按时间排序?6. 一道关于 JavaScript 中 this 的题目的困惑7. 取不出SQL得到的当前页8. android-studio - android app微信登录一定要申请了登录权限才能测试?9. javascript - 如何为大量的sprite添加碰撞检测框?10. mysql多表查询

网公网安备