像C++ sort(), Java sort()和其他语言一样, Python还提供了内置函数来进行排序。
排序函数可用于按升序和降序对列表进行排序。
以升序对列表进行排序。
句法
# This will sort the given list in ascending order.
# It returns a sorted list according to the passed parameter.
List_name.sort()
此函数可用于对整数,浮点数,字符串等列表进行排序。
# 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 – If true, the list is sorted in descending order
key – function that serves as a key for the sort comparison
# 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)]
请参阅Python Sort文章,以获取更多Python排序文章。
感谢奋斗者在这个主题上的投入。