Sort the array of strings first by length, then alphabetically in Python 3

How to sort an array in python firstly by word length (from 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 already sort alphabetically with print (sorted(WordsArray)):

['Lorem', 'adipiscing', 'amet', 'consectetur', 'do', 'dolor', 'eiusmod', 'elit', 'incididunt', 'ipsum', 'sed', 'sit', 'tempor']
+4
source share
2 answers

First, the use will only not sort alphabetically , look at your result ... I'm sure it doesn’t get to . What you are doing now is case -sensitive sorting .sortedLa

Key Function :

>>> 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']

Key Function, , , :

>>> 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']
+4

, -len(x), x:

sorted(WordsArray, key=lambda x: (-len(x),x))

, ex aequo , -len(x) , , .

, , x, .

, : Python , ord(..) .. , . :

sorted(WordsArray, key=lambda x: (-len(x),x.lower()))

: , , est-zet ss .. . .

+3

Source: https://habr.com/ru/post/1686619/


All Articles