ChatGPT와 Python의 documentation의 실습 결과인데 공유하고자 올린다.
주요 특징
- sorted(): 어떤 이터러블 객체든 정렬 가능
- reverse=True: 내림차순 정렬, default는 오름차순 정렬이다.
- key=함수: 정렬 기준 지정
- 안정적 정렬(stable sort): 동일한 값의 원래 순서 유지
- 시간 복잡도: O(n log n)
sorted의 결과는 원본 리스트는 변환하지 않으며 다른 리스트로 추가로 저장할 수 있다.
a = [5, 2, 3, 1, 4]
b = sorted(a)
print(a) #[5, 2, 3, 1, 4]
print(b) #[1, 2, 3, 4, 5]
반면에 sort는 기존의 리스트를 정렬하는 in-place 형태의 메소드다.
a = [5, 2, 3, 1, 4]
a.sort()
a
[1, 2, 3, 4, 5]
기본 사용법
# 단순 리스트 정렬
numbers = [3, 1, 4, 1, 5, 9, 2]
# 오름차순 정렬, Ascending Order
sorted_numbers = sorted(numbers) # [1, 1, 2, 3, 4, 5, 9]
print(sorted_numbers)
# 내림차순 정렬, Descending Order
desc_numbers = sorted(numbers, reverse=True) # [9, 5, 4, 3, 2, 1, 1]
print(desc_numbers )
Key 파라미터 사용
# 문자열 길이로 정렬
words = ['banana', 'pie', 'apple', 'kiwi']
sorted_by_length = sorted(words, key=len) # ['pie', 'kiwi', 'apple', 'banana']
# 딕셔너리 값으로 정렬
student_tuples = [
{'name': 'John', 'score': 80},
{'name': 'Alice', 'score': 95},
{'name': 'Bob', 'score': 85}
]
sorted_students = sorted(student_tuples, key=lambda x: x['score'])
sorted_students
>> [{'name': 'John', 'score': 80},
{'name': 'Bob', 'score': 85},
{'name': 'Alice', 'score': 95}]
복잡한 정렬 조건
1. 튜플 사용
# 여러 기준으로 정렬 (튜플 사용)
student_tuples = [
('John', 'A', 15),
('Jane', 'B', 12),
('Dave', 'A', 10)
]
sorted_students = sorted(student_tuples, key=lambda x: (x[1], x[2]))
sorted_students
>> [('Dave', 'A', 10), ('John', 'A', 15), ('Jane', 'B', 12)]
2. Class object 사용
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
sorted(student_objects, key=lambda student: student.age) # sort by age
>> [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
itemgetter로 정렬하기
from operator import itemgetter
sorted(student_tuples, key=itemgetter(2))
>> [('Dave', 'A', 10), ('Jane', 'B', 12), ('John', 'A', 15)]
attrgetter로 정렬하기
from operator import attrgetter
sorted(student_objects, key=attrgetter('age'))
>> [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
sorted(student_objects, key=attrgetter('grade', 'age'))
>> [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
References:
Sorting Techniques — Python 3.13.2 documentation
'개발 > Python' 카테고리의 다른 글
Python dealing with time (0) | 2025.04.21 |
---|---|
파이썬의 여러 가상환경 비교 (0) | 2024.08.03 |
Anaconda와 가상 환경 관리 (0) | 2024.08.01 |
파이썬의 None과 NaN (0) | 2024.07.12 |