python中怎么对列表以区间进行统计?
阿神
阿神 2017-04-18 10:23:00
0
2
931

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的频率?抱歉题目描述的不好

阿神
阿神

闭关修行中......

reply all(2)
巴扎黑
# code for python3
from itertools import groupby

lst = [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)

Result:

{'91-100': 5, '1-10': 19}

Questions I answered: Python-QA

黄舟
# coding: utf-8

lst = [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] += 1
print intervals
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template