我试图使用计数器按出现次数对字母进行排序,并将具有相同频率的任何字母按字母顺序排列,但我无法访问它生成的字典的值.
letter_count = collections.Counter("alphabet")
print(letter_count)
生产:
Counter({'a': 2, 'l': 1, 't': 1, 'p': 1, 'h': 1, 'e': 1, 'b': 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)]
如果您希望输出仍然是dict,可以将其转换为collections.OrderedDict:
>>> collections.OrderedDict(a)
# OrderedDict([('a', 2),
# ('b', 1),
# ('e', 1),
# ('h', 1),
# ('l', 1),
# ('p', 1),
# ('t', 1)])
如您所见,这保留了订购. ‘a’首先是因为它最常见.其他所有内容都按字母顺序排序.
标签:python,python-3-x,python-collections