Ordenar significa ordenar el conjunt de valors de manera creixent o decreixent. Hi ha diversos mètodes per ordenar valors a Python. Podem emmagatzemar un conjunt o grup de valors utilitzant diverses estructures de dades com ara llista, tuples, diccionaris que depèn de les dades que estem emmagatzemant. Per tant, en aquest article, parlarem d'alguns mètodes i criteris per ordenar les dades a Python.
Mètode Sorted().
Aquest és un mètode predefinit a Python que ordena qualsevol tipus d'objecte.
Sintaxi:
sorted(iterable, key, reverse)>
En aquest mètode, passem 3 paràmetres, dels quals 2 (clau i invers) són opcionals i el primer paràmetre, és a dir, iterable pot ser qualsevol objecte iterable. Aquest mètode retorna una llista ordenada però no canvia l'estructura de dades original.
Exemple 1:
Python 3
# 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))> |
>
quina és la mida del meu monitor
>
['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']>
Exemple 2:
Utilitzant una funció predefinida com a paràmetre clau. Així que el segon paràmetre és a dir. clau s'utilitza per ordenar l'estructura de dades donada per alguna funció predefinida, com ara només () o alguna funció definida per l'usuari. Ordena els valors de l'estructura de dades en funció de la funció passat al paràmetre clau.
Python 3
# 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>))> |
>
>Sortida
Sorting without key parameter: ['apple', 'ball', 'cat', 'dog'] Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']>
Exemple 3:
Ús de la funció definida per l'usuari per al paràmetre clau.
Python 3
# 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))> |
>
>
Sortida
Classificació sense paràmetre clau: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
Ordenant amb by_name com a paràmetre clau: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
Ordenant amb by_marks com a paràmetre clau: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]
Exemple 4:
Doncs el El tercer paràmetre és invers que s'utilitza per ordenar l'iterable en ordre descendent o decreixent.
Python 3
Expressions java lambda
# 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>))> |
>
>Sortida
Sorting without key parameter: ['for', 'geeks', 'geeks'] Sorting with len as key parameter: ['geeks', 'geeks', 'for']>
Exemple 5:
Utilitzant els tres paràmetres
Python 3
on és la configuració del navegador
# 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>))> |
>
>
Sortida
Ordenant sense clau i invers: [(‘Amar’, 89), (‘Lasya’, 32), (‘Ramesh’, 56), (‘Reka’, 54)]
Ordenant amb by_name com a paràmetre clau i el paràmetre invers com a Fals: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
Ordenant amb by_name com a paràmetre clau i el paràmetre invers com a True: [('Reka', 54), ('Ramesh', 56), ('Lasya', 32), ('Amar', 89)]
Ordenant amb by_marks com a paràmetre clau i el paràmetre invers com a Fals: [(‘Lasya’, 32), (‘Reka’, 54), (‘Ramesh’, 56), (‘Amar’, 89)]
Ordenant amb by_marks com a paràmetre clau i el paràmetre invers com a True: [('Amar', 89), ('Ramesh', 56), ('Reka', 54), ('Lasya', 32)]
Mètode Sort().
Aquest mètode ordena la llista en ordre ascendent per defecte, i podem utilitzar el paràmetre invers per ordenar en ordre descendent. Aquest mètode canvia la llista original i no retorna res.
Exemple 1:
Python 3
Heapify sort
# 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)> |
>
>Sortida
Original list: ['geeks', 'for', 'geeks'] Sorted list: ['for', 'geeks', 'geeks']>
Exemple 2:
Utilitzant una funció predefinida com a paràmetre clau
Python 3
# 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)> |
>
>Sortida
Original List: ['apple', 'ball', 'cat', 'dog'] Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']>
Exemple 3:
Utilitzant una funció definida per l'usuari com a paràmetre clau
Python 3
# 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)> |
>
>
Sortida
llista original: [(‘Ramesh’, 56), (‘Reka’, 54), (‘Lasya’, 32), (‘Amar’, 89)]
Ordenant amb by_name com a paràmetre clau: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
llista original: [(‘Ramesh’, 56), (‘Reka’, 54), (‘Lasya’, 32), (‘Amar’, 89)]
Ordenant amb by_marks com a paràmetre clau: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]
Exemple 4:
Utilitzant el paràmetre invers
Python 3
a b c nombres
# 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)> |
>
>Sortida
original list: ['geeks', 'for', 'geeks'] sorting with reverse parameter ['geeks', 'geeks', 'for']>