Lista Pythona Metoda sort()
Przykład
Posortuj listę alfabetycznie:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
Definicja i użycie
Metoda sort()
domyślnie sortuje listę rosnąco.
Możesz także utworzyć funkcję, która decyduje o kryteriach sortowania.
Składnia
list.sort(reverse=True|False, key=myFunc)
Wartości parametrów
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) |
Więcej przykładów
Przykład
Sortuj listę malejąco:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
Przykład
Posortuj listę według długości wartości:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
Przykład
Sortuj listę słowników na podstawie wartości „roku” słowników:
# 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)
Przykład
Posortuj listę według długości wartości i odwróć:
# 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)