如何将排序后的dict保存到元组列表中?

2024-09-25 02:37:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题可能很容易解决,但我是一个Python初学者,不能这样做。你知道吗

b = input()
a = b.split()
from collections import Counter
myDict = Counter(a)
import operator
test_dict = myDict
wynik = sorted(test_dict.items(), key=operator.itemgetter(1))
print(wynik)

为什么wynik没有排序?你知道吗


Tags: keyfromtestimportinputcounteritemsoperator
1条回答
网友
1楼 · 发布于 2024-09-25 02:37:54

您的数据已排序。按值的升序排列。如果要按降序排列计数,请使用reverse=True反转排序顺序:

sorted(test_dict.items(), key=operator.itemgetter(1), reverse=True)

请注意,您不需要自己排序;请改用^{} method

wynik = test_dict.most_common()

此方法已按降序返回键和计数:

>>> from collections import Counter
>>> counts = Counter('abc abc qwerty abc bla bla bla abc'.split())
>>> counts.most_common()
[('abc', 4), ('bla', 3), ('qwerty', 1)]

相关问题 更多 >