Sort Counter by frequency, then alphabetically in Python

陌路散爱 提交于 2019-11-28 01:52:46

问题


I am trying to use counter to sort letters by occurrence, and put any that have the same frequency into alphabetical order, but I can't get access to the Value of the dictionary that it produces.

letter_count = collections.Counter("alphabet")
print(letter_count)

produces:

Counter({'a': 2, 'l': 1, 't': 1, 'p': 1, 'h': 1, 'e': 1, 'b': 1})

How can I get it ordered by frequency, then by alphabetical order, so everything that shows up only once is in alphabetical order?


回答1:


It sounds like your question is how to sort the entire list by frequency, then break ties alphabetically. You can sort the entire list like this:

>>> a = sorted(letter_count.items(), key=lambda item: (-item[1], item[0]))
>>> print(a)
# [('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]

If you want the output to be a dict still, you can convert it into a collections.OrderedDict:

>>> collections.OrderedDict(a)
# OrderedDict([('a', 2),
#              ('b', 1),
#              ('e', 1),
#              ('h', 1),
#              ('l', 1),
#              ('p', 1),
#              ('t', 1)])

This preserves the ordering, as you can see. 'a' is first because it's most frequent. Everything else is sorted alphabetically.




回答2:


For the sake of completeness, to get the single-occurrence letters in alphabetical order:

letter_count = collections.Counter("alphabet")

single_occurrences = sorted([letter for letter, occurrence in letter_count.items() if occurrence == 1])
print(single_occurrences)
# prints: ['b', 'e', 'h', 'l', 'p', 't']



回答3:


You can try this:

letter_count = collections.Counter("alphabet")

the_letters = [a for a, b in letter_count.items() if b == 1]
letters.sort()
print("letters that occur only once:")

for i in the_letters:
     print(i)

This code creates a list of all letters that occur only once by using list comprehension, and then prints them all. items() returns a key-value pair, which can be used to determine if the value of a key is equal to one.



来源:https://stackoverflow.com/questions/44076269/sort-counter-by-frequency-then-alphabetically-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!