在生成直方图时,我通常使用collections.Counter,它有一个内置的.most_common()方法。你可以像字典一样传递一个计数器到另一个计数器,它将以你想象的方式工作。在>>> test_dict = {1: 6, 2: 8, 3: 2, 4: 4, 5: 8, 6: 4, 7: 10, 8: 3, 9: 7}
>>> c = Counter(test_dict)
# returns a list of tuples with the (item, count) values.
>>> c.most_common()
[(7, 10), (2, 8), (5, 8), (9, 7), (1, 6), (4, 4), (6, 4), (8, 3), (3, 2)]
# if you want only the counts:
>>> [count for item, count in c.most_common()]
[10, 8, 8, 7, 6, 4, 4, 3, 2]
# if you want only the objects:
>>> [item for item, count in c.most_common()]
[7, 2, 5, 9, 1, 4, 6, 8, 3]
# if you want them in reverse order
>>> [item for item, count in c.most_common()][::-1]
[3, 8, 6, 4, 1, 9, 5, 2, 7]
从基于列表的输入创建原始计数的某个子集的counter对象非常简单。您可以使用函数:
^{pr2}$
或者,如果您只想要结果,您可以像这样包括您的列表:my_list = [1, 4, 5]
>>> [count for item, count in c.most_common() if item in my_list]
[8, 6, 4]