Python – How to sort a 2d array by different order for each element?

I just want to clear out that I am new to coding.
I am trying to solve a problem set that counts the occurrence of characters in a string and prints out the 3 most reoccurring characters

Heres the code I wrote

    s = input().lower()
    b =  []
    for i in s:
        templst = []
        if templst not in b:

    final = sorted(b, key=itemgetter(1),reverse=True)
    print (final)
    for i in final[:3]:
        print(*i, sep=" ")

now if I gave it an input of


the output of final would be

[['o', 12], ['m', 11], ['w', 11], ['n', 11], ['t', 9], ['v', 9], ['i', 9], ['p', 9], ['s', 8], ['z', 8], ['r', 8], ['b', 8], ['g', 8], ['k', 8], ['y', 7], ['c', 7], ['q', 7], ['h', 7], ['a', 6], ['j', 6], ['u', 6], ['d', 5], ['f', 5], ['e', 5], ['x', 5], ['l', 5]

so, the most occurring characters are

['o', 12], ['m', 11], ['w', 11], ['n', 11]

instead of

['o', 12], ['m', 11], ['n', 11], ['w', 11]

and since "m", "w" and "n" occurred equal times how do I sort the first element alphabetically while having the second element reversely sorted

>Solution :

you need to specify multiple conditions for the sort

final= Sorted(b, key = lambda e: (-e[1], e[0]))

The negative sign here makes larger numbers first (as if we are sorting in reverse order)

Leave a Reply