English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La función sorted() devuelve una lista ordenada de manera iterativa desde los elementos.
La función sorted() devuelve una lista ordenada en un orden específico (AscendenteoDescendente) para ordenar los elementos iterables dados.
La sintaxis de sorted() es:
sorted(iterable, key=None, reverse=False)
La función sorted() puede usar hasta tres parámetros:
iterable-Secuencia (Cadena,Tupla,Lista) o conjunto (Conjunto,Diccionario,Conjunto congelado) o cualquier otro iterador.
reverse (opcional) -Si es True, la lista ordenada se invierte (o se ordena en orden descendente). Si no se proporciona, por defecto es False.
key (opcional) -Función utilizada como clave de comparación para el ordenamiento. Por defecto es None.
# Lista de vocales py_list = ['e', 'a', 'u', 'o', 'i'] print(sorted(py_list)) # String py_string = 'Python' print(sorted(py_string)) # Grupo de vocales py_tuple = ('e', 'a', 'u', 'o', 'i') print(sorted(py_tuple))
Output result
['a', 'e', 'i', 'o', 'u'] ['P', 'h', 'n', 'o', 't', 'y'] ['a', 'e', 'i', 'o', 'u']
Atención:La lista también tienesort()Método, su modo de ejecución es el mismo que el de sort(). La única diferencia es que el método sort() no devuelve ningún valor y cambia la lista original.
La función sorted() acepta un parámetro reverse como parámetro opcional.
Establecer reverse = True para ordenar los objetos iterables en orden de iteración.
# set py_set = {'e', 'a', 'u', 'o', 'i'} print(sorted(py_set, reverse = True)) # dictionary py_dict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5} print(sorted(py_dict, reverse = True)) # frozen set frozen_set = frozenset(('e', 'a', 'u', 'o', 'i')) print(sorted(frozen_set, reverse = True))
Output result
['u', 'o', 'i', 'e', 'a'] ['u', 'o', 'i', 'e', 'a'] ['u', 'o', 'i', 'e', 'a']
If you want to sort using your own implementation, then sort() also accepts a key function as an optional parameter.
You can sort the given iterable according to the result of the key function.
sorted(iterable, key=len)
len() is a built-in function in Python used to calculate the length of an object.
The list is sorted according to the length of the elements (from the lowest to the highest count).
# Sort by the second element def take_second(elem): return elem[1) # Random list random = (2, 2), (3, 4), (4, 1), (1, 3)] # Key sorted list sorted_list = sorted(random, key = take_second) # Print list print('Sorted list:', sorted_list)
Output result
Sorted list: (4, 1), (2, 2), (1, 3), (3, 4)]