当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python sort()用法及代码示例


像C++ sort(),Java sort()和其他语言一样,python还提供了内置的函数进行排序。

排序函数可用于按升序和降序对列表进行排序。

以升序对列表进行排序。


用法

List_name.sort()
This will sort the given list in ascending order.

此函数可用于对整数,浮点数,字符串等列表进行排序。

# List of Integers 
numbers = [1, 3, 4, 2] 
  
# Sorting list of Integers 
numbers.sort() 
  
print(numbers) 
  
# List of Floating point numbers 
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] 
  
# Sorting list of Floating point numbers 
decimalnumber.sort() 
  
print(decimalnumber) 
  
# List of strings 
words = ["Geeks", "For", "Geeks"] 
  
# Sorting list of strings 
words.sort() 
  
print(words)

输出:

[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['For', 'Geeks', 'Geeks']

以降序对列表进行排序。

用法

list_name.sort(reverse=True)
This will sort the given list in descending order.
# List of Integers 
numbers = [1, 3, 4, 2] 
  
# Sorting list of Integers 
numbers.sort(reverse=True) 
  
print(numbers) 
  
# List of Floating point numbers 
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] 
  
# Sorting list of Floating point numbers 
decimalnumber.sort(reverse=True) 
  
print(decimalnumber) 
  
# List of strings 
words = ["Geeks", "For", "Geeks"] 
  
# Sorting list of strings 
words.sort(reverse=True) 
  
print(words)

输出:

[4, 3, 2, 1]
[3.67, 3.28, 2.01, 2.0, 1.68]
['Geeks', 'Geeks', 'For']

用法:

list_name.sort() - it sorts in ascending order
list_name.sort(reverse=True) - it sorts in descending order
list_name.sort(key=…, reverse=…) - it sorts according to user’s choice

参数:
默认情况下,sort()不需要任何其他参数。但是,它有两个可选参数:

  • reverse -如果为true,则列表按降序排序
    key -用作排序比较键的函数

返回值:

It returns a sorted list according to the passed parameter.

# Python program to demonstrate sorting by user's 
# choice 
  
# function to return the second element of the 
# two elements passed as the parameter 
def sortSecond(val):
    return val[1]  
  
# list1 to demonstrate the use of sorting  
# using using second key  
list1 = [(1,2),(3,3),(1,1)] 
  
# sorts the array in ascending according to  
# second element 
list1.sort(key=sortSecond)  
print(list1) 
  
# sorts the array in descending according to 
# second element 
list1.sort(key=sortSecond,reverse=True) 
print(list1)

输出:

[(1, 1), (1, 2), (3, 3)]
[(3, 3), (1, 2), (1, 1)]

感谢奋斗者在此主题上的投入。



相关用法


注:本文由纯净天空筛选整理自ShivamKD大神的英文原创作品 sort() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。