所以基本上我想计算 float 出现在给定列表中的次数。例如:用户输入成绩列表(所有分数都为 100 分),并以 10 为一组进行排序。从 0-10、10-20、20-30.. 等等)的分数出现了多少次?比如考试成绩分布。我知道我可以使用计数功能,但由于我不是在寻找特定数字,所以我遇到了麻烦。有没有办法结合计数和范围?感谢您的帮助。
最佳答案
要对数据进行分组,请将其除以间隔宽度。要计算每组中的人数,请考虑使用 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()
关于Python - 计算列表中特定范围的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9543935/