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 - 請問數據庫字段為年月日,傳進的參數為月,怎么查詢那個月所對應的數據
