通过键对python中的计数器进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17930814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sorting a counter in python by keys
提问by corvid
I have a counter that looks a bit like this:
我有一个看起来像这样的计数器:
Counter: {('A': 10), ('C':5), ('H':4)}
I want to sort on keys specifically in an alphabetical order, NOT by counter.most_common()
我想按字母顺序专门对键进行排序,而不是按 counter.most_common()
is there any way to achieve this?
有没有办法实现这一目标?
采纳答案by falsetru
回答by Roman Pekar
>>> from operator import itemgetter
>>> from collections import Counter
>>> c = Counter({'A': 10, 'C':5, 'H':4})
>>> sorted(c.items(), key=itemgetter(0))
[('A', 10), ('C', 5), ('H', 4)]
回答by wwwilliam
In Python 3, you can use the most_commonfunction of collections.Counter:
在 Python 3 中,你可以使用collections.Counter的most_common函数:
x = ['a', 'b', 'c', 'c', 'c', 'd', 'd']
counts = collections.Counter(x)
counts.most_common(len(counts))
This uses the most_common function available in collections.Counter, which allows you to find the keys and counts of n
most common keys.
这使用了 collections.Counter 中可用的 most_common 函数,它允许您找到n
最常用键的键和计数。
回答by Recep ?en
To get values as list in sorted order
按排序顺序将值作为列表获取
array = [1, 2, 3, 4, 5]
counter = collections.Counter(array)
sorted_occurrences = list(dict(sorted(counter.items())).values())
回答by Calab
sorted(counter.items(),key = lambda i: i[0])
for example:
例如:
arr = [2,3,1,3,2,4,6,7,9,2,19]
c = collections.Counter(arr)
sorted(c.items(),key = lambda i: i[0])
outer: [(1, 1), (2, 3), (3, 2), (4, 1), (6, 1), (7, 1), (9, 1), (19, 1)] if you want to get the dictionary format,just
外层:[(1, 1), (2, 3), (3, 2), (4, 1), (6, 1), (7, 1), (9, 1), (19, 1) ] 如果你想得到字典格式,只要
dict(sorted(c.items(),key = lambda i: i[0]))