如何使用python代码获得成对的直方图编号? [英] How can I get histogram number with pairs by using python code?

查看:45
本文介绍了如何使用python代码获得成对的直方图编号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过使用 python 代码将 hist no 成对使用,就像我输入 11 2 34 21 时输出应该是这样的 11(1) 2(1) 34(1) 21(1)

解决方案

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

<预><代码>>>>v = ( 11, 2, 34, 21, 2, 2 )

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

<预><代码>>>>从集合导入计数器>>>ctr = 计数器(v)

现在,让我们获取您想要的计数:

<预><代码>>>>字典(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 文档中阅读有关 Counter 类的更多信息一>.

I want to take hist no with pairs by using python code like when i put input 11 2 34 21 the output should be like that 11(1) 2(1) 34(1) 21(1)

解决方案

First, let's create a list of numbers (I have added some repeats to make it more interesting):

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

Next, let's create a Counter instance:

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

Now, let's get the counts that you wanted:

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

If you prefer the parenthesized format that you show in the question, then we need to do some formatting:

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

You can read more about the Counter class in the python docs.

这篇关于如何使用python代码获得成对的直方图编号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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