공부/Python
python sorted 함수를 통한 리스트, 튜플, 문자열, 딕셔너리 정렬
빛나는나무
2024. 1. 22. 00:30
sorted 함수는 파이썬에서 리스트, 튜플, 문자열, 딕셔너리 등의 iterable 객체를 정렬하는 데 사용됩니다. 이 함수는 정렬된 새로운 리스트를 반환하며, 원본 데이터를 변경하지 않습니다. sorted 함수의 기본 사용법은 다음과 같습니다.
sorted(iterable, key=None, reverse=False)
iterable: 정렬하려는 iterable 객체를 나타냅니다 (리스트, 튜플, 문자열, 딕셔너리 등).
key (선택적): 정렬 기준을 제공하는 함수입니다. 기본값은 None이며, 이 경우에는 요소 자체의 값을 기준으로 정렬됩니다.
reverse (선택적): 기본값은 False이며, True로 설정하면 내림차순으로 정렬됩니다.
다음은 간단한 예제를 통해 sorted 함수의 사용법을 보여줍니다.
# 숫자 리스트를 정렬
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 출력: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# 문자열을 정렬
text = "python"
sorted_text = sorted(text)
print(sorted_text) # 출력: ['h', 'n', 'o', 'p', 't', 'y']
# 내림차순으로 정렬
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # 출력: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
key 매개변수를 사용하여 정렬 기준을 지정할 수도 있습니다. 이 경우에는 정렬에 사용될 값을 반환하는 함수를 제공합니다. 예를 들어, 절대값을 기준으로 정렬하는 경우
numbers = [-5, 3, -1, 8, -2, 7]
sorted_numbers_abs = sorted(numbers, key=abs)
print(sorted_numbers_abs) # 출력: [-1, -2, 3, -5, 7, 8]
딕셔너리의 경우
# 딕셔너리를 키를 기준으로 정렬
my_dict = {'apple': 3, 'banana': 1, 'orange': 5, 'grape': 2}
sorted_dict_keys = dict(sorted(my_dict.items()))
print(sorted_dict_keys)
# 결과: {'apple': 3, 'banana': 1, 'grape': 2, 'orange': 5}
# 딕셔너리를 값으로 기준으로 정렬
sorted_dict_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict_values)
# 결과: {'banana': 1, 'grape': 2, 'apple': 3, 'orange': 5}
첫 번째 예제에서는 sorted 함수를 사용하여 딕셔너리를 키를 기준으로 정렬합니다. 두 번째 예제에서는 key 매개변수를 람다 함수와 함께 사용하여 값을 기준으로 정렬합니다.
오브젝트 속성값의 경우
# 오브젝트의 속성을 기준으로 정렬
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Person 객체 리스트 생성
people = [Person('Alice', 30), Person('Bob', 25), Person('Charlie', 35)]
# 'age' 속성을 기준으로 객체 리스트 정렬
sorted_people = sorted(people, key=lambda person: person.age)
for person in sorted_people:
print(f"{person.name}: {person.age}세")
# 결과:
# Bob: 25세
# Alice: 30세
# Charlie: 35세
이 예제에서는 'age' 속성을 기준으로 Person 객체 리스트를 정렬하기 위해 sorted 함수를 사용합니다. key 매개변수는 'age' 속성을 비교하기 위한 람다 함수와 함께 활용됩니다.
리스트 안에 딕셔너리가 있는 경우
# 리스트 안에 딕셔너리가 있는 경우
people_list = [
{'name': 'Alice', 'age': 30, 'city': 'New York'},
{'name': 'Bob', 'age': 25, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 35, 'city': 'Los Angeles'}
]
# 'age'를 기준으로 딕셔너리 정렬
sorted_people = sorted(people_list, key=lambda person: person['age'])
for person in sorted_people:
print(f"Name: {person['name']}, Age: {person['age']}, City: {person['city']}")
이러한 방식으로 sorted 함수를 활용하여 다양한 데이터를 정렬할 수 있습니다.