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


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


列出 sort() 方法

sort() 方法用於對列表元素進行升序和降序排序,該方法用這個列表(其元素要排序)調用並接受一些可選參數(在參數下麵解釋),該方法不返回任何值,它對這個列表進行排序。

用法:

    List_name.sort(reverse=True|False, key=function)

參數:

  • reverse=True|False– 這是一個可選參數,默認值為False,按升序對列表元素進行排序,如果設置為True,則按降序對列表元素進行排序。
  • key=function– 它也是一個可選參數,可用於指定排序條件。

返回值:

這個方法的返回類型是<class 'NoneType'>,它什麽都不返回。

示例 1:不指定任何參數的排序列表

# Python List sort() Method with Example

# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before sort operation...")
print("cars:", cars)

# sorting the elements
cars.sort() # sorts in ascending order

# printing the list
print("cars after sort operation...")
print("cars:", cars)

輸出

cars before sort operation...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars after sort operation...
cars: ['Audi', 'Audi', 'BMW', 'Lexus', 'Porsche']

示例 2:指定第一個參數的排序列表

# Python List sort() Method with Example

# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before sort operation...")
print("cars:", cars)

# sorting the elements specifying reverse=True
cars.sort(reverse=True) 

# printing the list
print("cars list elements in descending order...")
print("cars:", cars)

# sorting the elements specifying reverse=False
cars.sort(reverse=False) 

# printing the list
print("cars list elements in ascending order...")
print("cars:", cars)

輸出

cars before sort operation...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars list elements in descending order...
cars: ['Porsche', 'Lexus', 'BMW', 'Audi', 'Audi']
cars list elements in ascending order...
cars: ['Audi', 'Audi', 'BMW', 'Lexus', 'Porsche']

示例 3:指定兩個參數的排序列表

# Python List sort() Method with Example

# defining a function that will return length
def getLen(e):
    return len(e)
    
# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before sort operation...")
print("cars:", cars)

# sorting the elements specifying reverse=True
cars.sort(reverse=True,key=getLen) 

# printing the list
print("cars list elements in descending order based on length...")
print("cars:", cars)

# sorting the elements specifying reverse=False
cars.sort(reverse=False,key=getLen) 

# printing the list
print("cars list elements in ascending order based on length...")
print("cars:", cars)

輸出

cars before sort operation...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars list elements in descending order based on length...
cars: ['Porsche', 'Lexus', 'Audi', 'Audi', 'BMW']
cars list elements in ascending order based on length...
cars: ['BMW', 'Audi', 'Audi', 'Lexus', 'Porsche']


相關用法


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