I have been trying to sort a list of elements (string) according to their occurrence in Python3. I have been using the inbuilt sort()
method with the string.count
as key as shown below.
p = "acaabbcabac"
print(sorted(p, key=p.count))
# Output : ['c', 'b', 'b', 'c', 'b', 'c', 'a', 'a', 'a', 'a', 'a']
#But expected output is ['a','a','a','a','a','b','b','b','c','c','c']
p = "acaabbcb"
print(sorted(p, key=p.count))
# Output : ['c', 'c', 'a', 'a', 'a', 'b', 'b', 'b']
#Output is as expected
p = "ababab"
print(sorted(p, key=p.count))
# Output :['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
#But expected output is ['a','a','a','b','b','b']
What I have observed is, the above sort works as per the occurrence of the element, but it works only if the counts of each element is different. If the occurrence of any two or more elements is same, then they are listed in the same order they appear in the string/list.
Am I doing something wrong or is there a better approach at this ? I tried searching answers for this issue but I could not find and so am posting this here.
Thanks in advance.