Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 = []
        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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading