Funció Python sorted().
Funció ordenada () de Python retorna una llista ordenada. No només està definit per a la llista i accepta qualsevol iterable (llista, tupla, cadena, etc.).
Exemple
Python 3
print> (> sorted> ([> 4> ,> 1> ,> 3> ,> 2> ]))> |
Sortida
[1, 2, 3, 4]
Sintaxi de la funció Python sorted().
ordenat (iterable, clau, invers)
Paràmetres:
- Iterable: seqüència (llista, tupla, cadena) o col·lecció (diccionari, conjunt, conjunt congelat) o qualsevol altre iterador que calgui ordenar.
- clau (opcional): Una funció que serviria com a clau o com a base de comparació d'ordenació.
- Revés (opcional): Si és cert, l'iterable s'ordenaria en ordre invers (descendente), per defecte s'estableix com a Fals.
Tornada: Retorna una llista amb els elements ordenats.
Com utilitzar la funció ordenada () a Python?
Utilitzar la funció sortd() és molt fàcil. És una funció integrada a Python i es pot utilitzar amb qualsevol iterable. Entenem-ho millor amb un exemple:
Exemple:
Python 3
# creating a list> counting> => [> 4> ,> 1> ,> 5> ,> 2> ,> 3> ]> #print sorted list> print> (> sorted> (counting))> |
Sortida
[1, 2, 3, 4, 5]
Més exemples de funcions Sorted().
Vegem alguns dels casos d'ús de la funció sortd():
1. Ordenar una llista de Python mitjançant la funció sortd().
En aquest exemple, hem aplicat l'ordenació a Llista de Python .
Python 3
x> => [> 2> ,> 8> ,> 1> ,> 4> ,> 6> ,> 3> ,> 7> ]> > print> (> 'Sorted List returned :'> ,> sorted> (x))> > print> (> 'Reverse sort :'> ,> sorted> (x, reverse> => True> ))> > print> (> '
Original list not modified :'> , x)> |
Sortida
Sorted List returned : [1, 2, 3, 4, 6, 7, 8] Reverse sort : [8, 7, 6, 4, 3, 2, 1] Original list not modified : [2, 8, 1, 4, 6, 3, 7]
2. Ordenar diferents tipus de dades amb la funció sortd().
En aquest exemple, hem utilitzat sortd() en diferents tipus de dades com ara llista, tupla , corda, diccionari , conjunt i conjunt congelat.
Python 3
# List> x> => [> 'q'> ,> 'w'> ,> 'r'> ,> 'e'> ,> 't'> ,> 'y'> ]> print> (> sorted> (x))> > # Tuple> x> => (> 'q'> ,> 'w'> ,> 'e'> ,> 'r'> ,> 't'> ,> 'y'> )> print> (> sorted> (x))> > # String-sorted based on ASCII translations> x> => 'python'> print> (> sorted> (x))> > # Dictionary> x> => {> 'q'> :> 1> ,> 'w'> :> 2> ,> 'e'> :> 3> ,> 'r'> :> 4> ,> 't'> :> 5> ,> 'y'> :> 6> }> print> (> sorted> (x))> > # Set> x> => {> 'q'> ,> 'w'> ,> 'e'> ,> 'r'> ,> 't'> ,> 'y'> }> print> (> sorted> (x))> > # Frozen Set> x> => frozenset> ((> 'q'> ,> 'w'> ,> 'e'> ,> 'r'> ,> 't'> ,> 'y'> ))> print> (> sorted> (x))> |
Sortida
['e', 'q', 'r', 't', 'w', 'y'] ['e', 'q', 'r', 't', 'w', 'y'] ['h', 'n', 'o', 'p', 't', 'y'] ['e', 'q', 'r', 't', 'w', 'y'] ['e', 'q', 'r', 't', 'w', 'y'] ['e', 'q', 'r', 't', 'w', 'y']
3. Ordenació inversa utilitzant Python sorted()
Ordenar una cadena en ordre lexicogràfic invers per configuració reverse=Veritat a la funció ordenat().
Python 3
# Python3 code to demonstrate> # Reverse Sort a String> # using join() + sorted() + reverse> > # initializing string> test_string> => 'geekforgeeks'> > # printing original string> print> (> 'The original string : '> +> str> (test_string))> > # using join() + sorted() + reverse> # Sorting a string> res> => ''.join(> sorted> (test_string, reverse> => True> ))> > # print result> print> (> 'String after reverse sorting : '> +> str> (res))> |
Sortida
The original string : geekforgeeks String after reverse sorting : srokkggfeeee
4. Python Sorted() amb lambda
Utilitzant sortd() dins de la funció lambda de Python.
Python 3
import> functools> test_string> => 'geekforgeeks'> > print> (> 'The original string : '> +> str> (test_string))> # using sorted() + reduce() + lambda> res> => functools.> reduce> (> lambda> x, y: x> +> y,> > sorted> (test_string,> > reverse> => True> ))> print> (> 'String after reverse sorting : '> +> str> (res))> |
Sortida
The original string : geekforgeeks String after reverse sorting : srokkggfeeee
5. Ordenat() a Python amb len()
En aquest exemple, estem ordenant la llista en funció de la seva longitud. La corda de la longitud més petita hauria de ser primer.
Python 3
L> => [> 'cccc'> ,> 'b'> ,> 'dd'> ,> 'aaa'> ]> print> (> 'Normal sort :'> ,> sorted> (L))> print> (> 'Sort with len :'> ,> sorted> (L, key> => len> ))> |
Sortida
Normal sort : ['aaa', 'b', 'cccc', 'dd'] Sort with len : ['b', 'dd', 'aaa', 'cccc']
La clau també pot prendre funcions definides per l'usuari com a valor per a la base de l'ordenació.
Exemple:
Python 3
# Sort a list of integers based on> # their remainder on dividing from 7> def> func(x):> > return> x> %> 7> > L> => [> 15> ,> 3> ,> 11> ,> 7> ]> > print> (> 'Normal sort :'> ,> sorted> (L))> print> (> 'Sorted with key:'> ,> sorted> (L, key> => func))> |
Sortida
Normal sort : [3, 7, 11, 15] Sorted with key: [7, 15, 3, 11]
6. Ordenar una llista en ordre ascendent amb sorted()
A my_list, tenim una llista de valors enters. A continuació, utilitzem la funció ordenada per ordenar la llista en ordre ascendent. La funció ordenada pren l'iterable per ordenar-se com a primer argument i retorna una llista nova que conté els elements ordenats.
A my_string, tenim una cadena. A continuació, fem servir la funció ordenada per ordenar els caràcters de la cadena en ordre ascendent. La funció ordenada tracta la cadena com un iterable de caràcters i retorna una llista nova que conté els caràcters ordenats.
A my_tuples, tenim una llista de tuples que conté nombres enters i cadenes. Hem utilitzat la funció ordenada per ordenar la llista en funció del segon element de cada tupla. Per aconseguir-ho hem passat una funció lambda com a argument clau per a la funció ordenada.
Python 3
my_list> => [> 3> ,> 1> ,> 4> ,> 1> ,> 5> ,> 9> ,> 2> ,> 6> ,> 5> ]> sorted_list> => sorted> (my_list)> print> (sorted_list)> > my_string> => 'hello, world!'> sorted_string> => sorted> (my_string)> print> (sorted_string)> > my_tuples> => [(> 1> ,> 'one'> ), (> 3> ,> 'three'> ), (> 2> ,> 'two'> ), (> 4> ,> 'four'> )]> sorted_tuples> => sorted> (my_tuples, key> => lambda> x: x[> 1> ])> print> (sorted_tuples)> |
Sortida
[1, 1, 2, 3, 4, 5, 5, 6, 9] [' ', '!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
7. Ordenar una llista de diccionaris per una clau específica mitjançant sorted()
En aquest exemple, estem ordenant la llista de diccionaris amb una clau específica.
Python 3
students> => [> > {> 'name'> :> 'John'> ,> 'age'> :> 20> },> > {> 'name'> :> 'Alice'> ,> 'age'> :> 18> },> > {> 'name'> :> 'Bob'> ,> 'age'> :> 22> }> ]> sorted_students> => sorted> (students,key> => lambda> x: x[> 'age'> ])> print> (sorted_students)> |
Sortida
[{'name': 'Alice', 'age': 18}, {'name': 'John', 'age': 20}, {'name': 'Bob', 'age': 22}] 8. Ordenar una llista d'objectes personalitzats
En aquest exemple, estem creant una classe personalitzada anomenada Persona amb dues variables d'instància nom i edat i estem creant tres objectes de la classe Persona i inserint objectes a les llistes. Estem utilitzant la funció Sorted que ordena els objectes de la persona.
Python 3
class> Person:> > def> __init__(> self> , name, age):> > self> .name> => name> > self> .age> => age> > > def> __repr__(> self> ):> > return> f> 'Person(name='{self.name}', age={self.age})'> > > people> => [> > Person(> 'John'> ,> 25> ),> > Person(> 'Alice'> ,> 18> ),> > Person(> 'Bob'> ,> 30> )> ]> sorted_people> => sorted> (people, key> => lambda> x: x.age)> print> (sorted_people)> |
Sortida
[Person(name='Alice', age=18), Person(name='John', age=25), Person(name='Bob', age=30)]
Hem tractat la definició, la sintaxi i els exemples de la funció sortd() a Python. Espero que això hagi respost la vostra pregunta sobre Com utilitzar la funció ordenada a Python?.
La funció sortd() no s'ha de confondre amb el mètode de llista sort(), ja que són diferents.
Espero que aquest article us hagi ajudat a entendre la funció sortd() a Python.