count.most_common函数
时间: 2024-02-09 14:11:37 浏览: 26
count.most_common函数是Python中collections模块中的一个函数,它可以用来统计一个可迭代对象中各个元素出现的次数,并按照出现次数从大到小排序。具体使用方法如下:
```python
from collections import Counter
# 创建一个列表
lst = [1, 2, 3, 2, 2, 4, 5, 5, 5, 5]
# 使用Counter统计每个元素出现的次数
count = Counter(lst)
# 使用most_common函数按照出现次数从大到小排序
most_common = count.most_common()
print(most_common)
# 输出:[(5, 4), (2, 3), (1, 1), (3, 1), (4, 1)]
```
在上面的例子中,lst列表中元素1出现了1次,元素2出现了3次,元素3、4、5分别出现了1、1、4次。使用Counter统计后,得到一个字典对象,其中key为元素,value为出现次数。使用most_common函数对字典进行排序后,得到一个元素为元组的列表,元组中第一个元素为元素本身,第二个元素为出现次数。
相关问题
python中count.most_common函数作用
等于b返回0,a大于b返回1
private static int compareArray(int[] a, int[] b) {
`collections.Counter` 中的 `most_common()` 函数可以用来返回出现次数最多的元素及其出现次 for (int i = 0; i < a.length; i++) {
if (a[i] < b[i]) {
return数,返回的结果是一个列表,其中每个元素都是一个由元素和出现次数组成的元 -1;
} else if (a[i] > b[i]) {
return 1;
}
}
return 0组。例如:
```
from collections import Counter
lst = ['apple', 'banana', 'apple', 'orange', 'apple', ';
}
}
```
注释在代码中,可以帮助理解。为了方便测试,我在代码中已banana', 'pear']
cnt = Counter(lst)
print(cnt.most_common())
```
输出的结果为:
```
[('apple',经预设了每个进程已经分配和需要的资源数,以及每种资源的总数和可用 3), ('banana', 2), ('orange', 1), ('pear', 1)]
```
这表示在列表 `lst数。你可以直接运行程序并输入每个进程依次请求的资源数,程序会模拟银行家` 中,出现次数最多的元素是 `apple`,它出现了 3 次,其次是 `算法并输出安全序列、当前时刻的资源分配表和每个进程请求的资源后的资源分配表。
import matplotlib.pyplot as plt from collections import Counter # 获取出现次数最多的前10个元素 counter = Counter(investors_list) most_common = counter.most_common(10) # 将元素名称和出现次数分别存储在两个列表中 names = [x[0] for x in most_common][::-1] # 改为降序排列 counts = [x[1] for x in most_common][::-1] # 改为降序排列 # 绘制水平柱状图 plt.barh(names, counts, color='green') # 更换颜色为绿色 # 设置图表标题和坐标轴标签 plt.title('Top 10 Investors') plt.xlabel('Count') plt.ylabel('Investor') # 显示图表 plt.show(),修改代码在柱状图柱体顶部加上数据标签
可以使用 plt.text() 函数在柱体顶部添加数据标签。代码如下:
```
import matplotlib.pyplot as plt
from collections import Counter
# 获取出现次数最多的前10个元素
counter = Counter(investors_list)
most_common = counter.most_common(10)
# 将元素名称和出现次数分别存储在两个列表中
names = [x[0] for x in most_common][::-1] # 改为降序排列
counts = [x[1] for x in most_common][::-1] # 改为降序排列
# 绘制水平柱状图
plt.barh(names, counts, color='green') # 更换颜色为绿色
# 在柱体顶部添加数据标签
for i, v in enumerate(counts):
plt.text(v + 0.5, i, str(v), color='blue', fontsize=12)
# 设置图表标题和坐标轴标签
plt.title('Top 10 Investors')
plt.xlabel('Count')
plt.ylabel('Investor')
# 显示图表
plt.show()
```
这样就可以在柱体顶部添加数据标签了,效果如下图所示:
![带数据标签的柱状图](https://img-blog.csdnimg.cn/20210917160708902.png)