Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
# 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)

結果:

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

我回答過的問題: Python-QA


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...