Python - 计算列表中某些范围的出现次数 [英] Python - Count occurrences of certain ranges in a list

查看:29
本文介绍了Python - 计算列表中某些范围的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我想计算一个浮点在给定列表中出现的次数.例如:用户输入一个等级列表(100 分中的所有分数),它们以十个为一组进行排序.0-10、10-20、20-30..等)的分数出现多少次?比如考试成绩分布.我知道我可以使用计数功能,但由于我不是在寻找特定数字,因此遇到了麻烦.有没有结合计数和范围的方法?感谢您的帮助.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆