python - 按值排序后如何按字母顺序对字典的键进行排序?
问题描述
from collections import Counter
with open("text.txt", encoding='utf-8') as file:
data = file.read()
words = data.split()
count_dict = dict(Counter(words))
for key, value in sorted(count_dict.items(), key=lambda x: x[1], reverse=True):
print(f'{key}: {value} time(s)')
对于文件:
abc
aab
abc
abb
abb
这返回:
abc: 2 time(s)
abb: 2 time(s)
aab: 1 time(s)
虽然它应该返回:
abb: 2 time(s)
abc: 2 time(s)
aab: 1 time(s)
在按次数(值?
解决方案
需要稍作改动:
等效的方法是使用计数的负值,而不是指定sorted
函数reverse-True 。现在我们正在使用计数的负数进行升序排序,我们可以使用包含作为“辅助列”的键的组合键进行排序:
for key, value in sorted(count_dict.items(), key=lambda x: (-x[1], x[0])):
print(f'{key}: {value} time(s)')
把它们放在一起:
from collections import Counter
with open("text.txt", encoding='utf-8') as file:
data = file.read()
words = data.split()
count_dict = dict(Counter(words))
for key, value in sorted(count_dict.items(), key=lambda x: (-x[1], x[0])):
print(f'{key}: {value} time(s)')
印刷
abb: 2 time(s)
abc: 2 time(s)
aab: 1 time(s)
推荐阅读
- html - 您如何加载有效的 dart 准系统网站?
- vtk - 错误:在 /vtk/IO/Import/vtkOBJImporter.cxx
- python - 将函数的返回值与用户输入的 Tkinter 进行比较
- swift - SwiftUI 上的 glassmorphic 卡片问题(图片)
- awk - awk 在找到另一个字符串后用新行(一次)替换字符串
- r - 如何合并以更新具有相同 col 名称的两个 dfs?
- android-ndk - ndk 二进制文件引用的共享库路径问题
- spring - Spring Boot Security:为什么 Strict-Transport-Security 标头不包括预加载;当 preload 设置为 true
- html - CSS网格指定第一列并为未知剩余设置小数单位
- java - 仅检索表视图行的非空值