排序函数可用于按升序,降序或用户定义的顺序对列表进行排序。
以升序对列表进行排序。
List_name.sort()
This will sort the given list in ascending order.
此函数可用于对整数,浮点数,字符串等列表进行排序。
numbers = [1, 3, 4, 2]
# Sorting list of Integers in ascending
numbers.sort()
print(numbers)
输出:
[1, 2, 3, 4]
以降序对列表进行排序。
list_name.sort(reverse=True)
This will sort the given list in descending order.
numbers = [1, 3, 4, 2]
# Sorting list of Integers in descending
numbers.sort(reverse = True)
print(numbers)
输出:
[4, 3, 2, 1]
使用用户定义的顺序对用户进行排序。
list_name.sort(key=…, reverse=…) - it sorts according to user’s choice
# 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)]
注:本文由纯净天空筛选整理自kartik大神的英文原创作品 Python list sort()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。