Metoda sort() seznamu v Pythonu
Příklad
Seřadit seznam podle abecedy:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
Definice a použití
Metoda sort()
standardně třídí seznam vzestupně.
Můžete také vytvořit funkci pro rozhodování o kritériích řazení.
Syntax
list.sort(reverse=True|False, key=myFunc)
Hodnoty parametrů
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) |
Další příklady
Příklad
Seřadit seznam sestupně:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
Příklad
Seřaďte seznam podle délky hodnot:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
Příklad
Seřaďte seznam slovníků podle hodnoty „roku“ slovníků:
# 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)
Příklad
Seřaďte seznam podle délky hodnot a obráceně:
# 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)