[파이썬] 튜플 정렬 방법 예제

튜플(Tuples)을 정렬하는 방법에 대한 예제를 제공하겠습니다. 튜플은 불변(immutable)하므로 정렬할 때 새로운 튜플을 생성하게 됩니다. 정렬은 sorted() 함수나 튜플 메서드를 사용하여 수행할 수 있습니다.

1. sorted() 함수 사용:

sorted() 함수를 사용하여 튜플을 정렬할 수 있습니다. 이 함수는 새로운 정렬된 리스트를 반환합니다.

# 정렬할 튜플
numbers = (3, 1, 4, 1, 5, 9, 2, 6)

# 오름차순으로 정렬
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

# 내림차순으로 정렬
reverse_sorted_numbers = sorted(numbers, reverse=True)
print(reverse_sorted_numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

2. tuple 메서드와 sorted() 함수 조합:

tuple 메서드를 사용하여 정렬된 튜플을 생성할 수도 있습니다.

# 정렬할 튜플
fruits = ('banana', 'cherry', 'apple')

# 오름차순으로 정렬된 튜플 생성
sorted_fruits = tuple(sorted(fruits))
print(sorted_fruits)  # ('apple', 'banana', 'cherry')

# 내림차순으로 정렬된 튜플 생성
reverse_sorted_fruits = tuple(sorted(fruits, reverse=True))
print(reverse_sorted_fruits)  # ('cherry', 'banana', 'apple')

3. 튜플 요소의 특정 속성을 기준으로 정렬:

튜플의 요소가 복합 데이터 구조라면 특정 속성을 기준으로 정렬할 수 있습니다. 이를 위해 key 매개변수를 사용합니다.

# 복합 데이터 구조를 포함한 튜플 리스트
people = [
    ('Alice', 25),
    ('Bob', 30),
    ('Eve', 22)
]

# 나이를 기준으로 오름차순 정렬
sorted_people = sorted(people, key=lambda x: x[1])
print(sorted_people)  # [('Eve', 22), ('Alice', 25), ('Bob', 30)]

튜플을 정렬하는 방법은 데이터의 종류와 요구사항에 따라 다를 수 있습니다. 이러한 예제를 통해 튜플을 효과적으로 정렬하는 방법을 이해하고 활용할 수 있을 것입니다.