當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python List sort()用法及代碼示例

Python list sort() 函數可用於按升序、降序或用戶定義的順序對 List 進行排序。

按升序對列表進行排序

用法:

List_name.sort()

這將按升序對給定列表進行排序。此函數可用於對整數、浮點數、字符串等列表進行排序。

範例1:按升序對列表進行排序

Python3


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

輸出:



[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']

按降序對列表進行排序

用法:

list_name.sort(反向=真)

這將按降序對給定列表進行排序。

範例2:按降序對列表進行排序

Python3


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=...) - 根據用戶的選擇排序

參數:

  • reverse:reverse=True 將列表降序排序。默認為反向=假
  • key:指定排序標準的函數

範例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)]





注:本文由純淨天空篩選整理自kartik大神的英文原創作品 Python List sort() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。