Python provides two sorting methods for a list object, one is to use the built-in function sort
of the list object, the other is to use the sorted
function to sort. The difference between the two sort methods is that the sorted
function does not change the original list and returns a sorted list.
1. Sort list elements use the list object’s built-in method sort.
- List object sort function definition.
list.sort(key=None,reverse=False)
- Example.
>>> list = [9,8,1,2,3,4,5,6] >>> >>> list.sort() >>> >>> print(list) [1, 2, 3, 4, 5, 6, 8, 9] >>> # Reverse list the elements. >>> list.sort(reverse=True) >>> >>> list [9, 8, 6, 5, 4, 3, 2, 1] # Define a function, this function will return the first element of the input x object. >>> def fuc(x): ... return x[0] ... # Define a python list object, each element is a tuple. >>> list = [(2, 'python'), (1, 'java'), (3,'javascript')] >>> >>> # Invoke the list object sort method, pass the function name to the key parameter. The key parameter accepts the first element of each tuple element in the list and determines the overall ranking according to the ranking of the first element of each tuple. >>> list.sort(key=fuc) >>> # Print out the list object values. >>> list [(1, 'java'), (2, 'python'), (3, 'javascript')]
2. Sort list elements using the python built-in function sorted.
- The
sorted
method is similar to thesort
method, except thatsorted
method does not change the original list and returns a new ordered list. andlist.sort ()
will change the original list. - The
list.sort()
method can only sort lists, whilesorted()
method can sort any data structures. - Example.
>>> list = [9,8,1,2,3,4,5,6] >>> >>> list_1 = sorted(list) >>> >>> list [9, 8, 1, 2, 3, 4, 5, 6] >>> >>> list_1 [1, 2, 3, 4, 5, 6, 8, 9] >>> # The sorted function also support reverse argument. >>> list_1 = sorted(list, reverse=True) >>> >>> list_1 [9, 8, 6, 5, 4, 3, 2, 1] >>> >>> list_1 = sorted(list, reverse=False) >>> >>> list_1 [1, 2, 3, 4, 5, 6, 8, 9] # The sorted function also supports the key argument. # Define a function which return the python dictionary object's score value. >>> def fuc(x): ... return x['score'] ... # Create a data list, each list element is a python dictionary object. >>> user_score=[{'name':'tom','score':100},{'name':'Ivy','score':99}] >>> # Sort the original user_score data list, pass the function name to the key argument, then the sorted function will sort the element by the dictionary object score value. >>> list_1 = sorted(user_score,key=fuc) >>> >>> list_1 [{'name': 'Ivy', 'score': 99}, {'name': 'tom', 'score': 100}] >>> >>> user_score [{'name': 'tom', 'score': 100}, {'name': 'Ivy', 'score': 99}]