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


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。