按频率排序计数器,然后按字母顺序 Python

Sort Counter by frequency, then alphabetically in Python

我正在尝试使用计数器按出现次数对字母进行排序,并将任何具有相同频率的字母按字母顺序排列,但我无法访问它生成的字典的值。

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

产生:

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

我怎样才能让它按频率排序,然后按字母顺序排列,这样所有只出现一次的东西都按字母顺序排列?

你可以试试这个:

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)

此代码使用列表推导创建只出现一次的所有字母的列表,然后将它们全部打印出来。 items() returns键值对,可用于判断某个键的值是否等于1

听起来你的问题是如何按频率对整个列表进行排序,然后按字母顺序打破平局。您可以像这样对 整个列表 进行排序:

>>> 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)]

如果你希望输出仍然是一个字典,你可以将它转换成一个collections.OrderedDict:

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

如您所见,这保留了顺序。 'a' 是第一个,因为它最常见。其他所有内容均按字母顺序排序。

为了完整起见,按字母顺序获取单次出现的字母:

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']

您可以在将输入传递给计数器之前对其进行排序。

>>> Counter(sorted("alphabet")).most_common()
[('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]