Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list by length and then in reverse alphabetical order

For example:

a=['a','b','zzz','ccc','ddd'] #before sorting

a=['b','a','zzz','ddd','ccc'] #after sorting

a.sort(key=len)

sorts the data but in alphabetical order but How to sort in the list by length and then in reverse alphabetical order ?

like image 647
Anwar Avatar asked Aug 15 '19 21:08

Anwar


2 Answers

Just use the reversed function:

a = list(reversed(sorted(a, key=lambda x: (-len(x), x))))

In [301]: a                                                                                                                                        
Out[301]: ['b', 'a', 'zzz', 'ddd', 'ccc']
like image 166
ivallesp Avatar answered Nov 03 '22 01:11

ivallesp


Here is another approach useing cmp_to_key() from functools:

import functools

def customsort(a, b):
    if len(a) != len(b):
        return -1 if len(a) < len(b) else 1
    else:
        if a < b:
            return 1
        elif a > b:
            return -1
        else:
            return 0

def main():
    a=['a','b','zzz','ccc','ddd']
    a.sort(key=functools.cmp_to_key(customsort))
    print(a)

main()

Output:

['b', 'a', 'zzz', 'ddd', 'ccc']
like image 24
Håkon Hægland Avatar answered Nov 02 '22 23:11

Håkon Hægland