Phương thức sắp xếp danh sách trong Python ()
Thí dụ
Sắp xếp danh sách theo thứ tự bảng chữ cái:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
Định nghĩa và Cách sử dụng
Phương sort()
pháp sắp xếp danh sách tăng dần theo mặc định.
Bạn cũng có thể tạo một hàm để quyết định (các) tiêu chí sắp xếp.
Cú pháp
list.sort(reverse=True|False, key=myFunc)
Giá trị tham số
Parameter | Description |
---|---|
reverse | Optional. reverse=True will sort the list descending. Default is reverse=False |
key | Optional. A function to specify the sorting criteria(s) |
Các ví dụ khác
Thí dụ
Sắp xếp danh sách giảm dần:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
Thí dụ
Sắp xếp danh sách theo độ dài của các giá trị:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
Thí dụ
Sắp xếp danh sách các từ điển dựa trên giá trị "năm" của các từ điển:
# A function that returns the 'year' value:
def myFunc(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
Thí dụ
Sắp xếp danh sách theo độ dài của các giá trị và đảo ngược:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)