排序是編程中非常基礎的操作之一,它可以幫助我們更好地組織和處理數據。在Python中,有多種方法可以對List進行排序。本文將從多個方面對使用Python對List進行排序的方法進行詳細闡述。
一、Python對List排序的基本方法
Python中對List進行排序的基本方法是使用sort()函數。sort()函數會直接修改原始數組。例如:
fruits = ['orange', 'apple', 'banana', 'pear', 'grape']
fruits.sort()
print(fruits)
輸出結果為:
['apple', 'banana', 'grape', 'orange', 'pear']
sort()函數還支持傳入一個reverse參數,用於指定排序方式。如:
fruits = ['orange', 'apple', 'banana', 'pear', 'grape']
fruits.sort(reverse=True)
print(fruits)
輸出結果為:
['pear', 'orange', 'grape', 'banana', 'apple']
二、使用sorted()函數對List排序
除了sort()函數之外,Python中還有一個與之類似的函數,即sorted()函數。與sort()函數不同的是,sorted()函數返回經過排序後的一個新的List,原始數組並不會被直接修改。
使用sorted()函數對List排序的方法如下:
fruits = ['orange', 'apple', 'banana', 'pear', 'grape']
new_fruits = sorted(fruits)
print(new_fruits)
print(fruits)
輸出結果為:
['apple', 'banana', 'grape', 'orange', 'pear']
['orange', 'apple', 'banana', 'pear', 'grape']
sorted()函數也支持傳入一個reverse參數,用於指定排序方式。如:
fruits = ['orange', 'apple', 'banana', 'pear', 'grape']
new_fruits = sorted(fruits, reverse=True)
print(new_fruits)
輸出結果為:
['pear', 'orange', 'grape', 'banana', 'apple']
三、自定義排序函數
有時候,使用Python內置的排序函數是無法滿足我們的需求的,需要我們自己編寫自定義排序函數。自定義排序函數需要滿足以下條件:
- 接受一個參數
- 返回一個用於比較大小的值
例如,我們要根據一個人的年齡和姓名進行排序:
people = [('Jack', 23), ('Tom', 32), ('Jerry', 18), ('Marry', 25)]
def age_name(person):
return person[1], person[0]
people.sort(key=age_name)
print(people)
輸出結果為:
[('Jerry', 18), ('Jack', 23), ('Marry', 25), ('Tom', 32)]
四、按照字典中某個鍵的值進行排序
在Python中,我們可以使用lambda表達式作為key參數來按照字典中某個鍵的值進行排序。例如:
fruits = [{'name':'orange', 'price':1.5},
{'name':'apple', 'price':3.0},
{'name':'banana', 'price':2.0},
{'name':'pear', 'price':1.8},
{'name':'grape', 'price':4.0}]
fruits.sort(key=lambda x: x['price'])
print(fruits)
輸出結果為:
[{'name': 'orange', 'price': 1.5},
{'name': 'pear', 'price': 1.8},
{'name': 'banana', 'price': 2.0},
{'name': 'apple', 'price': 3.0},
{'name': 'grape', 'price': 4.0}]
五、對List進行反轉
Python中對List進行反轉的方法是使用reverse()函數。reverse()函數會直接修改原始數組。例如:
fruits = ['orange', 'apple', 'banana', 'pear', 'grape']
fruits.reverse()
print(fruits)
輸出結果為:
['grape', 'pear', 'banana', 'apple', 'orange']
總結
Python中對List進行排序的方法有多種,包括直接使用sort()函數和使用sorted()函數,以及自定義排序函數;還可以按照字典中某個鍵的值進行排序。此外,Python中也提供了對List進行反轉的函數reverse()。通過掌握這些方法,我們可以更好地處理和操作數據。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/290733.html