Python ordinato() Funzione
Esempio
Ordina una tupla:
a = ("b", "g", "a", "d", "f", "c", "h", "e")
x = sorted(a)
print(x)
Definizione e utilizzo
La sorted()
funzione restituisce un elenco ordinato dell'oggetto iterabile specificato.
È possibile specificare l'ordine crescente o decrescente. Le stringhe sono ordinate alfabeticamente e i numeri sono ordinati numericamente.
Nota: non è possibile ordinare un elenco che contiene SIA valori stringa CHE valori numerici.
Sintassi
sorted(iterable, key=key, reverse=reverse)
Valori dei parametri
Parameter | Description |
---|---|
iterable | Required. The sequence to sort, list, dictionary, tuple etc. |
key | Optional. A Function to execute to decide the order. Default is None |
reverse | Optional. A Boolean. False will sort ascending, True will sort descending. Default is False |
Altri esempi
Esempio
Ordina numerico:
a = (1,
11, 2)
x = sorted(a)
print(x)
Esempio
Ordine crescente:
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)
Esempio
Ordine decrescente:
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a,
reverse=True)
print(x)