0

With this random string: 'bbbbcccaaaggggggghhhhhhhh'

I tried using the Counters to find the frequency of character

randomString = 'bbbbcccaaaggggggghhhhhhhh'
strCounter = Counter(randomString).most_common(5)

Yields the output of:

[('h', 8), ('g', 7), ('b', 4), ('c', 3), ('a', 3)]

In descending order of frequency. However 'c' and 'a' has the same frequency. How can I then sort such that most frequent character are first then characters with the same frequency is sorted by their ascii values (in ascending order)? E.g c = 99, a = 97

Desired output:

[('h', 8), ('g', 7), ('b', 4), ('a', 3), ('c', 3)]
  • A possibly better dupe: https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index - specifically https://stackoverflow.com/a/42241229/4349415 – Mike Scotty Sep 21 '21 at 10:33

1 Answers1

0

Try this:

sorted(strCounter, key=lambda tup: (-tup[1],tup[0]))
# [('h', 8), ('g', 7), ('b', 4), ('a', 3), ('c', 3)]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30