⬆️ ⬇️

Python: sorting lists by .sort () method with key - simple words

The reason to publish the post was that in a detailed study of lists (arrays) in Python, I could not find on the network any simple description of the method of sorting elements using the key: list.sort (key = ...).



Maybe, of course, I am so unlucky and I understand things that are simple for everyone for a long time, but I think that the information below will be very useful to the same beginner pythonists, like myself.



So what we have. Suppose we have a list that we would like to sort - and it consists of three rows of different lengths in a certain sequence:

')

sortList = ['a', '', 'bbb']



Sorting array elements with the .sort () method is done lexicographically by default — in simple terms, alphabetically, and also from a smaller value to a larger one. Therefore, if we do:



sortList.sort()



then we get the output:



>>> ['a', 'bbb', 'cc']



However, the .sort () method allows us to change both the principle and the sort order.



To change the sorting principle, use the key keyword, which has become available since Python 2.4.



Suppose we would like to sort our list in two ways: 1. in alphabetical order; 2. along the length of the string. The first method, however, already works as a default sorting, however we can achieve the same results with the key parameter:



sortList = ['a', 'cc', 'bbb']



# "" , :

def sortByAlphabet (inputStr):

return inputStr[0] # ,



# , :

def sortByLength (inputStr):

return len(inputStr) # ,



print u' : ', sortList # >>> ['a', 'cc', 'bbb']



sortList.sort( key=sortByAlphabet ) #

print u' : ', sortList # >>> ['a', 'bbb', 'cc']



sortList.sort( key=sortByLength ) #

print u' : ', sortList # >>> ['a', 'cc', 'bbb']



# , :

sortList.sort( key=sortByLength , reverse=True ) #

print u' , : ', sortList # >>> ['bbb', 'cc', 'a']




Note that the .sort () method acts on the source list by rearranging the elements within itself, and does NOT return a sorted copy of the source list. To get a sorted copy, use the sorted method:



newList = sorted(sortList)



- or the same option, but with the key parameter (as described above):



newList = sorted(sortList, key=sortByLength)



The .sorted () method has other parameters, but they seemed to me not so confusing for self-analysis.

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



All Articles