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

Question:

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 = []
        templst.append(i)
        templst.append(s.count(i))
        if templst not in b:
            b.append(templst)

    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

szrmtbttyyaymadobvwniwmozojggfbtswdiocewnqsjrkimhovimghixqryqgzhgbakpncwupcadwvglmupbexijimonxdowqsjinqzytkooacwkchatuwpsoxwvgrrejkukcvyzbkfnzfvrthmtfvmbppkdebswfpspxnelhqnjlgntqzsprmhcnuomrvuyolvzlni

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

Asked By: Mimz Ui

||

Answers:

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)

Answered By: Ahmed Sayed

Since pythons sort is stable you could do two sort passes:

b.sort(key=lambda x: x[0])
b.sort(key=lambda x: x[1], reverse=True)
Answered By: cafce25
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.