Python sort() 함수

Python sort() 함수 정렬된 목록을 반환합니다. 이는 목록에 대해 정의될 뿐만 아니라 모든 반복 가능한 항목(목록, 튜플, 문자열 등)을 허용합니다.

파이썬3




print> (> sorted> ([> 4> ,> 1> ,> 3> ,> 2> ]))>

산출

[1, 2, 3, 4] 

Python sorted() 함수 구문

정렬됨(반복 가능, 키, 역방향)

매개변수:

  • 반복 가능: 시퀀스(목록, 튜플, 문자열) 또는 컬렉션(사전, 집합, 고정 집합) 또는 정렬해야 하는 기타 반복자입니다.
  • 열쇠 (선택 과목): 정렬 비교의 키 또는 기초 역할을 하는 함수입니다.
  • 뒤집다 (선택 과목): True이면 iterable은 역순(내림차순)으로 정렬되며 기본적으로 False로 설정됩니다.

반품: 정렬된 순서로 요소가 포함된 목록을 반환합니다.

Python에서 sorted() 함수를 사용하는 방법은 무엇입니까?

sorted() 함수를 사용하는 것은 매우 쉽습니다. 이는 Python에 내장된 함수이며 모든 반복 가능 항목과 함께 사용할 수 있습니다. 예를 들어 더 잘 이해해 봅시다:

예:

파이썬3




# creating a list> counting> => [> 4> ,> 1> ,> 5> ,> 2> ,> 3> ]> #print sorted list> print> (> sorted> (counting))>

산출

[1, 2, 3, 4, 5] 

더 많은 Sorted() 함수 예제

sorted() 함수의 몇 가지 사용 사례를 살펴보겠습니다.

1. sorted() 함수를 사용하여 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)>

산출

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. sorted() 함수를 사용하여 다양한 데이터 유형 정렬

이 예에서는 목록과 같은 다양한 데이터 유형에 대해 sorted()를 사용했습니다. 튜플 , 끈, 사전 , 세트 및 냉동 세트.

파이썬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))>

산출

['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. Python sorted()를 사용한 역정렬

설정을 통해 문자열을 사전순 역순으로 정렬 역=참 sorted() 함수에서.

파이썬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))>

산출

The original string : geekforgeeks String after reverse sorting : srokkggfeeee 

4. 람다를 사용한 Python Sorted()

Python 람다 함수 내에서 sorted()를 사용합니다.

파이썬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))>

산출

The original string : geekforgeeks String after reverse sorting : srokkggfeeee 

5. len()을 사용하여 Python에서 Sorted()

이 예에서는 길이를 기준으로 목록을 정렬합니다. 가장 짧은 길이의 문자열이 먼저 와야 합니다.

파이썬3




L> => [> 'cccc'> ,> 'b'> ,> 'dd'> ,> 'aaa'> ]> print> (> 'Normal sort :'> ,> sorted> (L))> print> (> 'Sort with len :'> ,> sorted> (L, key> => len> ))>

산출

Normal sort : ['aaa', 'b', 'cccc', 'dd'] Sort with len : ['b', 'dd', 'aaa', 'cccc'] 

키는 정렬 기준에 대한 값으로 사용자 정의 함수를 사용할 수도 있습니다.

예:

파이썬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))>

산출

Normal sort : [3, 7, 11, 15] Sorted with key: [7, 15, 3, 11] 

6. sorted()를 사용하여 목록을 오름차순으로 정렬

my_list에는 정수 값 목록이 있습니다. 그런 다음 sorted 함수를 사용하여 목록을 오름차순으로 정렬합니다. 정렬된 함수는 정렬할 반복 가능한 항목을 첫 번째 인수로 사용하고 정렬된 요소가 포함된 새 목록을 반환합니다.

my_string에는 문자열이 있습니다. 그런 다음 sorted 함수를 사용하여 문자열의 문자를 오름차순으로 정렬합니다. 정렬된 함수는 문자열을 반복 가능한 문자로 처리하고 정렬된 문자가 포함된 새 목록을 반환합니다.

my_tuples에는 정수와 문자열을 포함하는 튜플 목록이 있습니다. 우리는 각 튜플의 두 번째 요소를 기준으로 목록을 정렬하기 위해 sorted 함수를 사용했습니다. 이를 달성하기 위해 람다 함수를 정렬 함수의 주요 인수로 전달했습니다.

파이썬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)>

산출

[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. sorted()를 사용하여 특정 키로 사전 목록 정렬

이 예에서는 특정 키를 사용하여 사전 목록을 정렬합니다.

파이썬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)>

산출

[{'name': 'Alice', 'age': 18}, {'name': 'John', 'age': 20}, {'name': 'Bob', 'age': 22}] 

8. 사용자 정의 개체 목록 정렬

이 예제에서는 두 개의 인스턴스 변수 name과 age를 사용하여 Person이라는 사용자 정의 클래스를 만들고 Person 클래스의 세 개체를 만들고 개체를 목록에 삽입합니다. 우리는 Person의 객체를 정렬하는 Sorted Function을 사용하고 있습니다.

파이썬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)>

산출

[Person(name='Alice', age=18), Person(name='John', age=25), Person(name='Bob', age=30)] 

우리는 Python에서 sorted() 함수의 정의, 구문 및 예를 다루었습니다. 이것이 Python에서 정렬 함수를 사용하는 방법에 대한 귀하의 질문에 대한 답변이 되었기를 바랍니다.

sorted() 함수는 sort() 목록 메서드와 다르기 때문에 혼동해서는 안 됩니다.

이 글이 Python의 sorted() 함수를 이해하는 데 도움이 되었기를 바랍니다.