Python3 List sort() Method

Python3 列表Python3 Lists


Description

The sort() function is used to sort the original list. If a parameter is specified, the specified comparison function is used.

Syntax

Syntax of the sort() method:

list.sort( key=None, reverse=False)

Parameters

Parameters

  • key -- Mainly used to compare elements. It has only one parameter, and the parameter of the specific function is taken from the iterable object, specifying an element in the iterable object for sorting.
  • reverse -- Sorting rule,reverse = Truedescending,reverse = Falseascending (default).

Return Value

This method does not return a value, but it sorts the objects of the list.

Example

The following example demonstrates how to use the sort() function:

Example

#!/usr/bin/python aList = ['Google', 'Example', 'Taobao', 'Facebook'] aList.sort() print ( "List : ", aList)

The output of the above example is as follows:

List :  ['Facebook', 'Google', 'Example', 'Taobao']

The following example outputs the list in descending order:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- # List vowels = ['e', 'a', 'u', 'o', 'i'] # Descending vowels.sort(reverse=True) # Output result print ( 'Descending output:', vowels )

The output of the above example is as follows:

降序输出: ['u', 'o', 'i', 'e', 'a']

The following example demonstrates how to output a list by specifying the sorting of elements in the list:

Example

#!/usr/bin/python # Get the second element of the list def takeSecond(elem): return elem[1] # List random = [(2, 2), (3, 4), (4, 1), (1, 3)] # Sort by the second element random.sort(key=takeSecond) # Output category print ('Sorted list:', random)

The output of the above example is as follows:

排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]

Python3 列表Python3 Lists

Other Extensions