logo

¿Cómo ordenar un conjunto de valores en Python?

Ordenar significa ordenar el conjunto de valores de manera creciente o decreciente. Existen varios métodos para ordenar valores en Python. Podemos almacenar un conjunto o grupo de valores utilizando varias estructuras de datos, como listas, tuplas y diccionarios, que dependen de los datos que estemos almacenando. Entonces, en este artículo, discutiremos algunos métodos y criterios para ordenar los datos en Python.

Método ordenado ()

Este es un método predefinido en Python que ordena cualquier tipo de objeto.

Sintaxis:



sorted(iterable, key, reverse)>

En este método, pasamos 3 parámetros, de los cuales 2 (clave e inverso) son opcionales y el primer parámetro, es decir, iterable, puede ser cualquier objeto iterable. Este método devuelve una lista ordenada pero no cambia la estructura de datos original.

Ejemplo 1:

Python3




# List> list_of_items>=> [>'g'>,>'e'>,>'e'>,>'k'>,>'s'>]> print>(>sorted>(list_of_items))> # Tuple> tuple_of_items>=> (>'g'>,>'e'>,>'e'>,>'k'>,>'s'>)> print>(>sorted>(tuple_of_items))> # String-sorted based on ASCII> # translations> string>=> 'geeks'> print>(>sorted>(string))> # Dictionary> dictionary>=> {>'g'>:>1>,>'e'>:>2>,>'k'>:>3>,>'s'>:>4>}> print>(>sorted>(dictionary))> # Set> set_of_values>=> {>'g'>,>'e'>,>'e'>,>'k'>,>'s'>}> print>(>sorted>(set_of_values))> # Frozen Set> frozen_set>=> frozenset>((>'g'>,>'e'>,>'e'>,>'k'>,>'s'>))> print>(>sorted>(frozen_set))>

>

métodos de cadena en java
>


Producción

['e', 'e', 'g', 'k', 's'] ['e', 'e', 'g', 'k', 's'] ['e', 'e', 'g', 'k', 's'] ['e', 'g', 'k', 's'] ['e', 'g', 'k', 's'] ['e', 'g', 'k', 's']>

Ejemplo 2:

Utilizando una función predefinida como parámetro clave. Entonces el segundo parámetro, es decir llave se utiliza para ordenar la estructura de datos dada mediante alguna función predefinida, como solo() o alguna función definida por el usuario. Ordena los valores en la estructura de datos según la función pasada al parámetro clave.

Python3




# using key parameter with pre-defined> # function i.e. len()> list_of_items>=> [>'apple'>,>'ball'>,>'cat'>,>'dog'>]> print>(>'Sorting without key parameter:'>,>sorted>(list_of_items))> print>(>'Sorting with len as key parameter:'>,>sorted>(list_of_items, key>=>len>))>

>

>

Producción

Sorting without key parameter: ['apple', 'ball', 'cat', 'dog'] Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']>

Ejemplo 3:

Usando la función definida por el usuario para el parámetro clave.

Python3




# using key parameter with user-defined> # function i.e. by_name> # using key parameter with user-defined> # function i.e. by_marks> # here is a list_of_tuples where the first> # item in tuple is the student name and the> # second item is his/her marks> list_of_items>=> [(>'Ramesh'>,>56>),(>'Reka'>,>54>),(>'Lasya'>,>32>),(>'Amar'>,>89>)]> # defining a user-defined function which returns> # the first item(name)> def> by_name(ele):> >return> ele[>0>]> # defining a user-defined function which returns> # the second item(marks)> def> by_marks(ele):> >return> ele[>1>]> print>(>'Sorting without key parameter:'>,>sorted>(list_of_items))> print>(>'Sorting with by_name as key parameter:'>,> >sorted>(list_of_items, key>=>by_name))> print>(>'Sorting with by_marks as key parameter:'>,> >sorted>(list_of_items, key>=>by_marks))>

>

cómo inicializar una matriz en java
>

Producción

Ordenar sin parámetro clave: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]

Ordenar con by_name como parámetro clave: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]

Ordenar con by_marks como parámetro clave: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]

Ejemplo 4:

Entonces el El tercer parámetro es inverso. que se utiliza para ordenar el iterable en orden descendente o decreciente.

Python3




# using key parameter reverse> list_of_items>=> [>'geeks'>,>'for'>,>'geeks'>]> print>(>'Sorting without key parameter:'>,> >sorted>(list_of_items))> print>(>'Sorting with len as key parameter:'>,> >sorted>(list_of_items, reverse>=>True>))>

>

>

Producción

Sorting without key parameter: ['for', 'geeks', 'geeks'] Sorting with len as key parameter: ['geeks', 'geeks', 'for']>

Ejemplo 5:

Usando los tres parámetros

Python3


cómo determinar el tamaño del monitor



# using by_name and by_marks as key parameter> # and making reverse parameter true> # here is a list_of_tuples where the first> # item in tuple is the student name and the> # second item is his/her marks> list_of_items>=> [(>'Ramesh'>,>56>), (>'Reka'>,>54>),> >(>'Lasya'>,>32>), (>'Amar'>,>89>)]> # defining a user-defined function which> # returns the first item(name)> def> by_name(ele):> >return> ele[>0>]> # defining a user-defined function which> # returns the second item(marks)> def> by_marks(ele):> >return> ele[>1>]> print>(>'Sorting without key and reverse:'>,>sorted>(list_of_items))> print>(>'Sorting with by_name as key parameter and reverse parameter as False:'>,> >sorted>(list_of_items, key>=>by_name, reverse>=>False>))> print>(>'Sorting with by_name as key parameter and reverse parameter as True:'>,> >sorted>(list_of_items, key>=>by_name, reverse>=>True>))> print>(>'Sorting with by_marks as key parameter and reverse parameter as False:'>,> >sorted>(list_of_items, key>=>by_marks, reverse>=>False>))> print>(>'Sorting with by_marks as key parameter and reverse parameter as True:'>,> >sorted>(list_of_items, key>=>by_marks, reverse>=>True>))>

>

>

Producción

Ordenación sin clave y al revés: [(‘Amar’, 89), (‘Lasya’, 32), (‘Ramesh’, 56), (‘Reka’, 54)]

Ordenar con by_name como parámetro clave y parámetro inverso como False: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]

Ordenar con by_name como parámetro clave y parámetro inverso como Verdadero: [('Reka', 54), ('Ramesh', 56), ('Lasya', 32), ('Amar', 89)]

Ordenar con by_marks como parámetro clave y parámetro inverso como False: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]

Ordenar con by_marks como parámetro clave y parámetro inverso como Verdadero: [('Amar', 89), ('Ramesh', 56), ('Reka', 54), ('Lasya', 32)]

Método ordenar()

Este método ordena la lista en orden ascendente de forma predeterminada y podemos usar el parámetro inverso para ordenar en orden descendente. Este método cambia la lista original y no devuelve nada.

Ejemplo 1:

Python3




# creating a list of items> list_of_items>=> [>'geeks'>,>'for'>,>'geeks'>]> print>(>'Original list:'>, list_of_items)> # using the sort method to sort> # the items> list_of_items.sort()> # displaying the list> print>(>'Sorted list:'>, list_of_items)>

>

>

Producción

Original list: ['geeks', 'for', 'geeks'] Sorted list: ['for', 'geeks', 'geeks']>

Ejemplo 2:

Usar una función predefinida como parámetro clave

Python3

np relleno




# using key parameter with pre-defined> # function i.e. len()> list_of_items>=> [>'apple'>,>'ball'>,>'cat'>,>'dog'>]> print>(>'Original List:'>, list_of_items)> # using the len() as key parameter and> # sorting the list> list_of_items.sort(key>=>len>)> print>(>'Sorting with len as key parameter:'>, list_of_items)>

>

>

Producción

Original List: ['apple', 'ball', 'cat', 'dog'] Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']>

Ejemplo 3:

Usar una función definida por el usuario como parámetro clave

Python3




# using key parameter with user-defined> # function i.e. by_name> # using key parameter with user-defined> # function i.e. by_marks> # defining a user-defined function which> # returns the first item(name)> def> by_name(ele):> >return> ele[>0>]> # defining a user-defined function which> # returns the second item(marks)> def> by_marks(ele):> >return> ele[>1>]> # here is a list_of_tuples where the first> # item in tuple is the student name and the> # second item is his/her marks> list_of_items>=> [(>'Ramesh'>,>56>), (>'Reka'>,>54>),> >(>'Lasya'>,>32>), (>'Amar'>,>89>)]> print>(>'original list:'>, list_of_items)> # sorting by key value as by_name function> list_of_items.sort(key>=>by_name)> print>(>'Sorting with by_name as key parameter:'>, list_of_items)> # here is a list_of_tuples where the first> # item in tuple is the student name and the> # second item is his/her marks> list_of_items>=> [(>'Ramesh'>,>56>), (>'Reka'>,>54>),> >(>'Lasya'>,>32>), (>'Amar'>,>89>)]> print>(>'original list:'>, list_of_items)> # sorting by key value as by_marks function> list_of_items.sort(key>=>by_marks)> print>(>'Sorting with by_marks as key parameter:'>, list_of_items)>

>

>

Producción

lista original: [(‘Ramesh’, 56), (‘Reka’, 54), (‘Lasya’, 32), (‘Amar’, 89)]

Ordenar con by_name como parámetro clave: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]

lista original: [(‘Ramesh’, 56), (‘Reka’, 54), (‘Lasya’, 32), (‘Amar’, 89)]

Ordenar con by_marks como parámetro clave: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]

Ejemplo 4:

Usando el parámetro inverso

Python3




convertir cadena a int en java

# using key parameter reverse> list_of_items>=> [>'geeks'>,>'for'>,>'geeks'>]> print>(>'original list:'>, list_of_items)> list_of_items.sort(reverse>=>True>)> print>(>'sorting with reverse parameter'>, list_of_items)>

>

>

Producción

original list: ['geeks', 'for', 'geeks'] sorting with reverse parameter ['geeks', 'geeks', 'for']>