Do you really understand sorted in Python? (recommended collection)

sorted(iterable,[reverse,key])

First, a brief look at the introduction of the sorted() method

sorted()
Operating principle:
    Take out the elements in the iterable data one by one and put them into the key function for processing.
    And sort according to the result of return in the function, return a new list
Function: Sort
parameter:
    iterable iterable data (container type data, range data sequence, iterator)
    reverse optional, whether to reverse, the default is False, no reverse, True reverse
    key is optional, function, it can be a custom function or a built-in function
Return value: sorted result
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

The most common use of sorted is to sort some numbers in ascending/descending order:

arr =  [ 3 , 7 , 1 , - 9 , 20 , 10 ] 
print ( sorted ( arr ) ) #default ascending order 
print ( sorted ( arr , reverse = True ) ) #reverse=True descending order
  • 1
  • 2
  • 3
[-9, 1, 3, 7, 10, 20]
[20, 10, 7, 3, 1, -9]
  • 1
  • 2

But sometimes we will encounter more complex problems, which may require some other restrictions on sorting results, etc.

For example: when you want to sort in ascending order according to the absolute value, you can pass in an abs() function

arr =  [ 3 , 7 , 1 , - 9 , 20 , 10 ] 
print ( sorted ( arr , key = abs ) ) #Set the reference function to abs()
  • 1
  • 2
[1, 3, 7, -9, 10, 20]
  • 1

Even if you want to sort in ascending order of even numbers first, and then sort in ascending order of odd numbers, then you need to customize a function func():

def  func ( num ) : 
    return num %  2

arr =  [ 3 , 2 , 4 , 6 , 5 , 7 , 9 ] 
print ( sorted ( arr , key = func ) )
  • 1
  • 2
  • 3
  • 4
  • 5
[2, 4, 6, 3, 5, 7, 9]
  • 1

If you want to be more concise, you can directly pass in alamda function

sorted ( arr , key = lambda x : x % 2 )
  • 1

sorted can also sort array/dictionary by key value:

array =  [ { "age" : 20 , "name" : "a" } , { "age" : 25 , "name" : "b" } , { "age" : 10 , "name" : "c" } ] 
array =  sorted ( array , key = lambda x : x [ "age" ] ) #Specify to sort by "age" in the dictionary
  • 1
  • 2
[{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
  • 1

First, sort by grade in descending order, and sort by name in ascending order of the same grade:

d1 =  [ { 'name' : 'alice' ,  'score' : 38 } ,  { 'name' : 'bob' ,  'score' : 18 } ,  { 'name' : 'darl' ,  'score' : 28 } ,  { 'name' : 'christ' ,  'score' : 28 } ] 
l =  sorted ( d1 ,key = lambda x : (- x [ 'score' ] , x [ 'name' ] ) ) #First sort by grades in descending order, then by name in ascending order 
print ( l )
  • 1
  • 2
  • 3
[{'name': 'alice', 'score': 38}, {'name': 'christ', 'score': 28}, {'name': 'darl', 'score': 28}, { 'name': 'bob', 'score': 18}]
  • 1

You can also specify which field to sort by:

#Assume L is a list of 3-tuples, where the elements of each tuple represent: name, age, salary 
L =  [ ( 'Bob' ,  25 , 4300 ) ,  ( 'Adam' ,  32 , 12000 ) ,  ( 'Bart' ,  16 , 2000 ) ,  ( 'Lisa' ,  48 , 9999 ) ] 
print ( sorted ( L , key = lambda x : x [ 0 ] ) ) #sort by name
print ( sorted ( L , key = lambda x : x [ 1 ] ) ) # sort by age 
print ( sorted ( L , key = lambda x : x [ 2 ] ) ) # sort by salary
  • 1
  • 2
  • 3
  • 4
  • 5
[('Adam', 32, 12000), ('Bart', 16, 2000), ('Bob', 25, 4300), ('Lisa', 48, 9999)]
[('Bart', 16, 2000), ('Bob', 25, 4300), ('Adam', 32, 12000), ('Lisa', 48, 9999)]
[('Bart', 16, 2000), ('Bob', 25, 4300), ('Lisa', 48, 9999), ('Adam', 32, 12000)]
  • 1
  • 2
  • 3

Sort by salary in descending order if age is the same:

L =  [ ( 'Bob' ,  25 , 4300 ) ,  ( 'Adam' ,  32 , 12000 ) ,  ( 'Bart' ,  32 , 2000 ) ,  ( 'Lisa' ,  48 , 9999 ) ] 
print ( sorted ( L , key = lambda x : ( x [ 1 ] , - x [ 2 ]) ) )
  • 1
  • 2
[('Bob', 25, 4300), ('Adam', 32, 12000), ('Bart', 32, 2000), ('Lisa', 48, 9999)]
  • 1

Tags: Do you really understand sorted in Python? (recommended collection)

Topics in Python python

Related: Do you really understand sorted in Python? (recommended collection)