如何使用python代码获得对的直方图编号?

时间:2016-05-07 04:59:58

标签: python-2.7

我想通过使用python代码对hist进行编号,就像我输入输入11 2 34 21时输出应该像11(1)2(1)34(1)21(1)

2 个答案:

答案 0 :(得分:1)

首先,让我们创建一个数字列表(我添加了一些重复以使其更有趣):

>>> v = ( 11, 2, 34, 21, 2, 2 )

接下来,让我们创建一个Counter实例:

>>> from collections import Counter
>>> ctr = Counter(v)

现在,让我们得到你想要的计数:

>>> dict(ctr)
{2: 3, 11: 1, 34: 1, 21: 1}

如果您更喜欢在问题中显示的带括号的格式,那么我们需要进行一些格式化:

>>> ' '.join('{}({})'.format(x, ctr[x]) for x in ctr)
'2(3) 11(1) 34(1) 21(1)'

您可以在python docs

中详细了解Counter类

答案 1 :(得分:0)

以下代码的效率低于@ John1024提出的解决方案。我发布它是为了能够提供一些关于如何创建直方图的额外见解。

我们首先生成一些随机整数:

>>> import random
>>> random.seed(123)    # to ensure reproducibility of results
>>> nums = [random.randint(10, 15) for i in range(12)]
>>> nums
[10, 10, 12, 10, 15, 10, 13, 11, 15, 10, 12, 12]

然后我们使用count()方法计算序列类型和generator expression的出现次数:

>>> counts = dict((n, nums.count(n)) for n in set(nums))

经过一些格式化(我使用的是Python 2.7),这就是我们得到的:

>>> ' '.join(['%g (%d)' % (n, counts[n]) for n in sorted(counts)])
'10 (5) 11 (1) 12 (3) 13 (1) 15 (2)'