python - 如何返回字符串中最常见的字母并根据它们的频率计数对它们进行排序
问题描述
我有这个字符串:s = "china construction bank"
。我想创建一个函数,返回 3 个最常见的字符,并按出现频率和出现次数对它们进行排序,但如果 2 个字符出现相同的次数,则应根据字母顺序对它们进行排序。我还想在单独的行中打印每个字符。
我现在已经构建了这段代码:
from collections import Counter
def ordered_letters(s, n=3):
ctr = Counter(c for c in s if c.isalpha())
print ''.join(sorted(x[0] for x in ctr.most_common(n)))[0], '\n', ''.join(sorted(x[0] for x in ctr.most_common(n)))[1], '\n', ''.join(sorted(x[0] for x in ctr.most_common(n)))[2]`
应用于上述字符串的这段代码将产生:
a
c
n
但这不是我真正想要的,我想要的输出是:
1st most frequent: 'n'. Appearances: 4
2nd most frequent: 'c'. Appearances: 3
3rd most frequent: 'a'. Appearances: 2
我被困在必须按字母顺序打印具有相同频率的字符的部分。我怎么能这样做?
非常感谢您提前
解决方案
您可以使用heapq.nlargest
自定义排序键。我们-ord(k)
用作辅助排序器以按升序排序。使用堆队列比sorted
不需要对Counter
对象中的所有项目进行排序要好。
from collections import Counter
from heapq import nlargest
def ordered_letters(s, n=3):
ctr = Counter(c.lower() for c in s if c.isalpha())
def sort_key(x):
return (x[1], -ord(x[0]))
for idx, (letter, count) in enumerate(nlargest(n, ctr.items(), key=sort_key), 1):
print('#', idx, 'Most frequent:', letter, '.', 'Appearances:', count)
ordered_letters("china construction bank")
# 1 Most frequent: n . Appearances: 4
# 2 Most frequent: c . Appearances: 3
# 3 Most frequent: a . Appearances: 2
推荐阅读
- django - 没有这样的表:form1_user
- c - 如果指针是在主线程中使用 malloc() 创建的,您如何在辅助线程中释放()缓冲区指针?
- python - Docker :openjdk:8-jdk-slim 即使在安装后也无法找到 pip
- c# - SQL Server Express 数据库表未更新
- javascript - 按下输入时单击表格内的下一步按钮
- javascript - 如何在不获取 O(n)^3 的情况下遍历包含 2D 数组的对象?
- listview - 如何在调试模式下禁用鼠标滚轮滚动点击
- java - 将子类转换为超类并调用两个类都具有的函数
- java - kotlin.time.Duration 和 java 反射
- c++ - 为什么 scanf() 没有变成两个浮点数