Home > Back-end >  Python - How to sort a 2d array by different order for each element?
Python - How to sort a 2d array by different order for each element?

Time:11-24

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

CodePudding user response:

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)

CodePudding user response:

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