Home  >  Article  >  Backend Development  >  How to use python sort function

How to use python sort function

藏色散人
藏色散人Original
2019-06-21 14:33:4332285browse

The python sort() function is used to sort the original list. If parameters are specified, the comparison function specified by the comparison function is used.

How to use python sort function

How to use the python sort function?

sort() method syntax:

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

Parameter

cmp -- Optional parameter, if this parameter is specified, the method of this parameter will be used for sorting.

key -- Mainly used for comparison elements, with only one parameter. The parameters of the specific function are taken from the iterable object, and an element in the iterable object is specified for sorting.

reverse -- Sorting rule, reverse = True for descending order, reverse = False for ascending order (default).

Return value

This method has no return value, but it will sort the objects in the list.

Example

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

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
aList = [123, 'Google', 'Runoob', 'Taobao', 'Facebook'];
 
aList.sort();
print "List : ", aList

The output results of the above example are as follows :

List :  [123, 'Facebook', 'Google', 'Runoob', 'Taobao']

The following examples output the list in descending order:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 列表
vowels = ['e', 'a', 'u', 'o', 'i']
 
# 降序
vowels.sort(reverse=True)
 
# 输出结果
print '降序输出:', vowels

The output results of the above examples are as follows:

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

The following example demonstrates outputting a list by sorting the elements in the specified list:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 获取列表的第二个元素
def takeSecond(elem):
    return elem[1]
 
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
 
# 指定第二个元素排序
random.sort(key=takeSecond)
 
# 输出类别
print '排序列表:', random

The output results of the above example are as follows:

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

Related recommendations:《Python Tutorial

The above is the detailed content of How to use python sort function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn