PortugalTheMan PortugalTheMan -3 years ago 241
Python Question

Sort string array first on length then alphabetically in Python 3

How to sort an array in python firstly by the length of the words (longest to shortest), and then alphabetically?

Here is what I mean:

I have this list:

WordsArray = ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt"]

I want to output this:
['consectetur', 'adipiscing', 'incididunt', 'eiusmod', 'tempor', 'dolor', 'ipsum', 'Lorem', 'amet', 'elit', 'sed', 'sit', 'do']

I can already sort alphabetically using
print (sorted(WordsArray))

['Lorem', 'adipiscing', 'amet', 'consectetur', 'do', 'dolor', 'eiusmod', 'elit', 'incididunt', 'ipsum', 'sed', 'sit', 'tempor']

Answer Source

Firstly, using just sorted will not sort alphabetically, look at your output... I am pretty sure L does not come before a. What you are currently doing is a case-sensitive sort.

You can perform a case-insensitive sort by using a Key Function like so:

>>> words_list = ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt"]
>>> sorted(words_list, key=str.lower)
['adipiscing', 'amet', 'consectetur', 'do', 'dolor', 'eiusmod', 'elit', 'incididunt', 'ipsum', 'Lorem', 'sed', 'sit', 'tempor']

You can then modify the Key Function like below to sort first on length then alphabetically:

>>> def custom_key(str):
...   return -len(str), str.lower()
>>> sorted(words_list, key=custom_key)
['consectetur', 'adipiscing', 'incididunt', 'eiusmod', 'tempor', 'dolor', 'ipsum', 'Lorem', 'amet', 'elit', 'sed', 'sit', 'do']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download