Python-计算列表中某些范围的出现 [英] Python - Count occurrences of certain ranges in a list
问题描述
因此,基本上,我想计算给定列表中出现浮点的次数.例如:用户输入了一个等级列表(所有分数均在100分之内),并且以十个为一组进行排序.从0-10、10-20、20-30 ..等得分出现多少次?像考试成绩分布.我知道我可以使用count函数,但是由于我没有在寻找特定的数字,因此遇到了麻烦.是否有结合数量和范围的途径?感谢您的帮助.
So basically I want to count the number of occurrences a floating point appears in a given list. For example: a list of grades (all scores out of 100) are inputted by the user and they are sorted in groups of ten. How many times do scores from 0-10, 10-20, 20-30.. etc) appear? Like test score distribution. I know I can use the count function but since I'm not looking for specific numbers I'm having trouble. Is there a away to combine the count and range? Thanks for any help.
推荐答案
要对数据进行分组,请将其除以间隔宽度.要计算每个组中的数字,请考虑使用 collections.Counter .这是一个带有文档和测试的示例:
To group the data, divide it by the interval width. To count the number in each group, consider using collections.Counter. Here's a worked out example with documentation and a test:
from collections import Counter
def histogram(iterable, low, high, bins):
'''Count elements from the iterable into evenly spaced bins
>>> scores = [82, 85, 90, 91, 70, 87, 45]
>>> histogram(scores, 0, 100, 10)
[0, 0, 0, 0, 1, 0, 0, 1, 3, 2]
'''
step = (high - low + 0.0) / bins
dist = Counter((float(x) - low) // step for x in iterable)
return [dist[b] for b in range(bins)]
if __name__ == '__main__':
import doctest
print doctest.testmod()
这篇关于Python-计算列表中某些范围的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!