📜  Python列表排序()方法

📅  最后修改于: 2022-05-13 01:55:38.008000             🧑  作者: Mango

Python列表排序()方法

Python list sort()函数可用于按升序、降序或用户定义的顺序对 List 进行排序。

按升序对列表进行排序

示例 1:按升序对列表进行排序

Python3
numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in ascending
numbers.sort()
  
print(numbers)


Python3
strs = ["geeks", "code", "ide", "practice"]
  
# Sorting list of Integers in ascending
strs.sort()
  
print(strs)


Python3
numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in descending
numbers.sort(reverse = True)
  
print(numbers)


Python
# 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, 2, 3, 4]

示例 1.1

Python3

strs = ["geeks", "code", "ide", "practice"]
  
# Sorting list of Integers in ascending
strs.sort()
  
print(strs)

输出:

['code', 'geeks', 'ide', 'practice']

按降序对列表进行排序

示例 2:按降序对列表进行排序

Python3

numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in descending
numbers.sort(reverse = True)
  
print(numbers)

输出:

[4, 3, 2, 1]

使用用户定义的顺序排序

示例 3:使用用户定义的顺序进行排序

Python

# 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)]