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()
is there any way to achieve this?
Just use sorted :
>>> from collections import Counter
>>> counter = Counter({'A': 10, 'C': 5, 'H': 7})
>>> counter.most_common()
[('A', 10), ('H', 7), ('C', 5)]
>>> sorted(counter.items())
[('A', 10), ('C', 5), ('H', 7)]
>>> 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)]
In Python 3, you can use the most_common function of collections.Counter:
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.
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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.