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)
在按次数(值?)排序后,如何按字母顺序放置单词(键)?
答案 0 :(得分:1)
需要稍作改动:
不是为 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)
答案 1 :(得分:1)
您可以将负号与 values
一起使用,然后像这样优先使用 keys
-
>>> from collections import Counter
>>> l = ["abc","aab","abc","abb","abb"]
>>> l
['abc', 'aab', 'abc', 'abb', 'abb']
>>> count_dict = Counter(l)
#### Negative Value is assigned to count_dict values
>>> sorted(count_dict.items(), key=lambda x: (-x[1],x[0]))
[('abb', 2), ('abc', 2), ('aab', 1)]
>>> 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)
>>>
答案 2 :(得分:0)
您希望值(数字)按降序排序,键(单词)按升序排序。你可以试试这个:
sorted(count_dict.items(), key=lambda x: (-x[1], x[0]))
排序键中的负值可以完成这项工作。