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)
关于python - 按值排序后如何按字母顺序对字典的键进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68468455/