【发布时间】:2017-07-12 01:56:53
【问题描述】:
我有一个计数器,我想按以下方式排序:
Counter({'M': 9, 'L': 5, 'P': 5, 'S': 2, 'd': 1, 'T': 1})
当我使用我的代码时,它给了我以下信息:
Counter({'M': 9, 'P': 5, 'L': 5, 'S': 2, 'T': 1, 'd': 1})
我尝试了sorted()函数,但是当我使用它时,它的返回值不再是一个计数器了。
这是我的代码,你会怎么做?
def most_encountered_letters(dictionnary):
counter = collections.Counter()
for line in dictionnary:
words = line.split(',')[0].split(' ')
for word in words:
counter[word[0]] += 1
print(counter)
return counter.most_common(5)
【问题讨论】:
-
A
Counter是Dict子类,因此根据定义它是未排序的,如果您尝试使用sorted()它必须返回非Dict类。您可以将结果移动到OrderedDict。我想,但我的问题是“你为什么要排序?”,因为您的实际问题可能会以另一种方式更好地解决。最后,这是lots of ways to sort。顺便说一句,Python 2.x 还是 3.x? -
在python中无法对
Dict进行排序,唯一的方法是查看链接stackoverflow.com/questions/613183/… -
要精确!您的 not-an-answer 彻底改变了您的问题,并使两个答案都无效。
-
另外,edit 你的头衔。你的标题说你想先按键排序,然后按值排序,但听起来你实际上想先按值排序,然后按键排序,这是相反的。