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 ?
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With