Python - 计算列表中某些范围的出现次数

use*_*457 4 python list count range histogram

所以基本上我想计算浮点出现在给定列表中的次数.例如:用户输入等级列表(所有得分均为100),并且它们以十个为一组进行分类.从0-10,10-20,20-30等分数出现多少次?像测试分数一样.我知道我可以使用计数功能,但因为我不是在找特定的数字,所以我遇到了麻烦.有没有结合计数和范围?谢谢你的帮助.

Ray*_*ger 7

要对数据进行分组,请将其除以间隔宽度.要计算每个组中的数字,请考虑使用collections.Counter.这是一个带有文档和测试的实例:

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()
Run Code Online (Sandbox Code Playgroud)

  • 我看起来像你在你之前写的所有四个答案.如果是这种情况,那么我会说,尽管你的答案可能是最好的,但也许不是所有其他的都值得投票,因为它们毕竟可能是有用的(即使它们都不是最好的). (4认同)

Sve*_*ach 6

如果您使用外部库NumPy可以,那么您只需要调用numpy.histogram():

>>> data = [82, 85, 90, 91, 70, 87, 45]
>>> counts, bins = numpy.histogram(data, bins=10, range=(0, 100))
>>> counts
array([0, 0, 0, 0, 1, 0, 0, 1, 3, 2])
>>> bins
array([   0.,   10.,   20.,   30.,   40.,   50.,   60.,   70.,   80.,
         90.,  100.])
Run Code Online (Sandbox Code Playgroud)