logo

Jak posortować zestaw wartości w Pythonie?

Sortowanie oznacza porządkowanie zbioru wartości w sposób rosnący lub malejący. Istnieją różne metody sortowania wartości w Pythonie. Możemy przechowywać zbiór lub grupę wartości, korzystając z różnych struktur danych, takich jak lista, krotki, słowniki, w zależności od przechowywanych danych. Dlatego w tym artykule omówimy niektóre metody i kryteria sortowania danych w Pythonie.

Metoda sortowania().

Jest to predefiniowana metoda w Pythonie, która sortuje dowolny rodzaj obiektu.

Składnia:



sql wybierz jako
sorted(iterable, key, reverse)>

W tej metodzie przekazujemy 3 parametry, z czego 2 (klucz i odwrotność) są opcjonalne, a pierwszym parametrem, tj. iterowalnym, może być dowolny iterowalny obiekt. Ta metoda zwraca posortowaną listę, ale nie zmienia oryginalnej struktury danych.

Przykład 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))>

>

>


Wyjście

['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']>

Przykład 2:

Używanie predefiniowanej funkcji jako kluczowego parametru. Zatem drugi parametr, tj. klucz służy do sortowania danej struktury danych według jakiejś predefiniowanej funkcji, takiej jak tylko() lub jakąś funkcję zdefiniowaną przez użytkownika. Sortuje wartości w strukturze danych na podstawie funkcji przekazanej do parametru klucza.

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>))>

>

>

Wyjście

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

Przykład 3:

Korzystanie z funkcji zdefiniowanej przez użytkownika dla parametru klucza.

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))>

>

>

Wyjście

Sortowanie bez parametru klucza: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]

Sortowanie według nazwy jako kluczowego parametru: [(‚Amar’, 89), (‚Lasya’, 32), (‚Ramesh’, 56), (‚Reka’, 54)]

Sortowanie z by_marks jako kluczowym parametrem: [(‚Lasya’, 32), (‚Reka’, 54), (‚Ramesh’, 56), (‚Amar’, 89)]

Przykład 4:

Więc Trzeci parametr jest odwrotny który służy do sortowania iterowalnego porządku malejącego lub malejącego.

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>))>

>

>

Wyjście

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

Przykład 5:

Używając wszystkich trzech parametrów

Python3




# 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>))>

>

>

Wyjście

Sortowanie bez klucza i rewersu: [(‚Amar’, 89), (‚Lasja’, 32), (‚Ramesz’, 56), (‚Reka’, 54)]

Sortowanie z parametrem według_nazwy jako parametrem kluczowym i parametrem odwrotnym jako False: [(‚Amar’, 89), (‚Lasya’, 32), (‚Ramesh’, 56), (‚Reka’, 54)]

Sortowanie z parametrem według_nazwy jako parametrem kluczowym i parametrem odwrotnym jako True: [(‚Reka’, 54), („Ramesh”, 56), („Lasya”, 32), („Amar”, 89)]

Sortowanie z by_marks jako parametrem kluczowym i parametrem odwrotnym jako False: [(‚Lasya’, 32), (‚Reka’, 54), (‚Ramesh’, 56), (‚Amar’, 89)]

Sortowanie z by_marks jako parametrem kluczowym i parametrem odwrotnym jako True: [(‚Amar’, 89), (‚Ramesh’, 56), (‚Reka’, 54), (‚Lasya’, 32)]

Metoda sortowania().

Ta metoda domyślnie sortuje listę w kolejności rosnącej, a możemy użyć parametru Reverse, aby posortować listę w kolejności malejącej. Ta metoda zmienia oryginalną listę i niczego nie zwraca.

Przykład 1:

Python3


co to jest nazwa użytkownika



# 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)>

>

>

Wyjście

pole listy HTML
Original list: ['geeks', 'for', 'geeks'] Sorted list: ['for', 'geeks', 'geeks']>

Przykład 2:

Używanie predefiniowanej funkcji jako kluczowego parametru

Python3




# 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)>

>

>

Wyjście

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

Przykład 3:

Używanie funkcji zdefiniowanej przez użytkownika jako parametru kluczowego

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)>

>

>

Wyjście

pierwotna lista: [(„Ramesz”, 56), („Reka”, 54), („Lasya”, 32), („Amar”, 89)]

Sortowanie według nazwy jako kluczowego parametru: [(‚Amar’, 89), (‚Lasya’, 32), (‚Ramesh’, 56), (‚Reka’, 54)]

pierwotna lista: [(„Ramesz”, 56), („Reka”, 54), („Lasya”, 32), („Amar”, 89)]

Sortowanie z by_marks jako kluczowym parametrem: [(‚Lasya’, 32), (‚Reka’, 54), (‚Ramesh’, 56), (‚Amar’, 89)]

Przykład 4:

Korzystanie z parametru odwrotnego

Python3




# 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)>

>

>

Wyjście

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