python 中列表怎么分区间统计
问题描述
list= [ ..., 2648, 2648, 2648, 63370, 63370, 425, 425, 120, 120, 217, 217, 189, 189, 128, 128, 115, 115, 197, 19752, 152, 152, 275, 275, 1716, 1716, 131, 131, 98, 98, 138, 138, 277, 277, 849, 302, 152, 1571, 68, 68, 102, 102, 92, 92, 146, 146, 155, 155, 9181, 9181, 474, 449, 98, 98, 59, 59, 295, 101, ...]for i in list: if int(i/50)+1 not in dic:dic(int(i /50)+1)=list.count(i) else:dic(int(i /50)+1)+=list.count(i)
我这么写总是报错,我想以 50bp 为一个区间进行统计,即统计长度在 0-50 的频数,50-100 的频数...
我这么写对么,应该怎么写呢?
问题解答
回答1:# code for python3from itertools import groupbylst= [ 2648, 2648, 2648, 63370, 63370, 425, 425, 120, 120, 217, 217, 189, 189, 128, 128, 115, 115, 197, 19752, 152, 152, 275, 275, 1716, 1716, 131, 131, 98, 98, 138, 138, 277, 277, 849, 302, 152, 1571, 68, 68, 102, 102, 92, 92, 146, 146, 155, 155, 9181, 9181, 474, 449, 98, 98, 59, 59, 295, 101, 5]for k, g in groupby(sorted(lst), key=lambda x: x//50): print(’{}-{}: {}’.format(k*50, (k+1)*50-1, len(list(g))))
結果:
0-49: 150-99: 10100-149: 15150-199: 8200-249: 2250-299: 5300-349: 1400-449: 3450-499: 1800-849: 11550-1599: 11700-1749: 22600-2649: 39150-9199: 219750-19799: 163350-63399: 2
不要使用內建函數的名字: list 作為變數名
你想要的區間重疊了, 比如說元素 50 就不知道要分在 0-50 還是 50-100 了
存取字典應該用 [] 而不是 ()
我回答過的問題: Python-QA
回答2:for i in list i是list中的内容,应该是for I in range(len(list))
相关文章:
1. python - Pycharm调试代码进行列表遍历时,如何直接赋值指定元素2. atom编译器 如何格式化前端代码文件?3. angular.js - Angular1使用bootstrap轮播条carousel不能自动轮播4. python - 基于scrapy-redis的分布式爬虫运行的时候不能正常运行 遇到的问题如下截图所示5. css3 - 我的css用less写的,eclipse的jsp文件要修改css很麻烦,怎么解决?6. android - 新建项目卡在Gradle:Resolvedependencies’:app:_debugCompile’7. javascript - webpack热加载配置不生效8. angular.js - 焦虑!angular的ng-options的问题9. Android Studio 中程序添加不上Xutils 3.0 jar包10. javascript - 关于在angularjs的select中遇到的问题!!