python - 按值排序后如何按字母顺序对字典的键进行排序?

标签 python python-3.x sorting

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/

相关文章:

python - 如何按轴对 numpy 数组进行排序并保留行

python - 当我尝试安装库时如何修复 python 中的 SSL 错误?

python - 如何记录特定时间的音频,直到在Python sounddevice中进行某些操作(如按下键盘)为止?

python - 如何按元素检查多个 pandas DataFrame.Series 的条件并将结果应用于新列?

python - 当我必须在长 pandas 系列(> 15 M 元素)中搜索时,如何优化 'enumerate'?

ruby 。如果日期相等,则获取数组的平均值

linux - 如何对文件列表进行排序并在 bash 中连接内容?

python - 如何在 GAE 上最好地设计日期/地理邻近查询?

python - 在基本操作系统(或 Ubuntu)上使用 python 3.8 而不是 3.6

python-3.x - Python 中带有类型提示的 2 个类的相互依赖