파이썬에서 Tuple을 정렬하는 방법을 소개합니다.
1. sorted()를 사용하여 Tuple 정렬
sorted(tuple, sort_fun)
으로 튜플을 정렬할 수 있습니다.
튜플은 데이터가 변경되지 않는 자료구조이기 때문에 정렬 후 리턴되는 리스트를 tuple()
으로 새로운 tuple을 생성해야 합니다.
정렬에 대한 규칙은 함수를 만들어 인자로 전달하면 됩니다. 아래 코드는 숫자를 내림차순으로 정렬합니다.
def sort_num(x):
return x
numbers = (10, 2, 11, 9, 7)
sorted_number = tuple(sorted(numbers, key=sort_num))
print(sorted_number)
Output:
(2, 7, 9, 10, 11)
function 대신 Lambda를 사용하여 Tuple 정렬
정렬에 대한 규칙을 함수로 만들지 않고 labmda 표현식으로 바로 전달할 수도 있습니다.
numbers = (10, 2, 11, 9, 7)
sorted_number = tuple(sorted(numbers, key=lambda x: x))
print(sorted_number)
Output:
(2, 7, 9, 10, 11)
Int와 String이 섞여있는 튜플 정렬
자료형이 다른 숫자가 섞여 있는 Tuple을 정렬할 때는 문자열을 Int로 변환하여 정렬하면 됩니다.
numbers = (10, '2', 11, 9, '7')
sorted_number = tuple(sorted(numbers, key=lambda x: int(x)))
print(sorted_number)
Output:
문자열 길이로 정렬하는 Tuple 예제
문자열 길이로 정렬하는 튜플 예제입니다.
def sort_len(x):
return len(x)
fruits = ('watermelon', 'kiwi', 'blueberry', 'apple')
sorted_fruits = tuple(sorted(fruits, key=sort_len))
print(sorted_fruits)
Output:
('kiwi', 'apple', 'blueberry', 'watermelon')
2. 튜플을 요소로 갖고 있는 리스트 정렬 : List.sort()
튜플을 갖고 있는 리스트를 정렬할 때는 List.sort()
로 정렬합니다.
리스트는 변형이 가능하기 때문에, sort()
호출 시, 리스트의 저장 순서가 변경됩니다. 새로운 리스트를 만들 필요가 없습니다.
튜플이 2개씩 데이터를 갖고 있는 경우, 첫번째 데이터로 정렬할지 두번째 데이터로 정렬할지 함수에서 정할 수 있습니다.
def sort_key(x):
return x[0]
def sort_value(x):
return x[1]
items = [('e', 5), ('a', 4), ('b', 3), ('c', 2), ('d', 1)]
items.sort(key=sort_key)
print(items)
items.sort(key=sort_value)
print(items)
Output:
[('a', 4), ('b', 3), ('c', 2), ('d', 1), ('e', 5)]
[('d', 1), ('c', 2), ('b', 3), ('a', 4), ('e', 5)]
위의 예제를 Lambda로 구현하면 다음과 같습니다.
tuples = [('e', 5), ('a', 4), ('b', 3), ('c', 2), ('d', 1)]
tuples.sort(key=lambda x: x[0])
print(tuples)
tuples.sort(key=lambda x: x[1])
print(tuples)
3. 반대로 튜플 정렬 : sort()에 reverse=True 인자 전달
정렬 규칙을 반대로 적용하려면 sort()
에 reverse=True
를 인자로 전달하면 됩니다.
tuples = [('e', 5), ('a', 4), ('b', 3), ('c', 2), ('d', 1)]
tuples.sort(key=lambda x: x[0], reverse=True)
print(tuples)
tuples.sort(key=lambda x: x[1], reverse=True)
print(tuples)
Output:
[('e', 5), ('d', 1), ('c', 2), ('b', 3), ('a', 4)]
[('e', 5), ('a', 4), ('b', 3), ('c', 2), ('d', 1)]
Loading script...
Related Posts
- Python - Requests 사용 방법 (GET/POST/PUT/PATCH/DELETE)
- Python - 온라인 컴파일러 사이트 추천
- Python - os.walk()를 사용하여 디렉토리, 파일 탐색
- Python - 문자열 비교 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트의 첫번째 요소 제거
- Python - 리스트의 마지막 요소 제거
- Python 소수점 버림, 4가지 방법
- Python 코드 안에서 버전 확인 방법
- Python 소수점 반올림, round() 예제
- Python - 리스트 평균 구하기, 3가지 방법
- Python - bytes를 String으로 변환하는 방법
- Python - String을 bytes로 변환하는 방법
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - dict 정렬 (Key, Value로 sorting)
- Python - 람다(Lambda) 함수 사용 방법
- Python - range() 사용 방법 및 예제
- Python - 리스트를 문자열로 변환
- Python - 문자를 숫자로 변환 (String to Integer, Float)
- Python - String split()으로 문자열 나누는 방법
- Python - 문자열 자르기 (slicing, substring)
- Python - File, Directory 경로 함수 소개
- Python - 작업 디렉토리, 실행 파일 경로 확인/변경 (pathlib)
- Python - 대문자/소문자 판별, 변환 방법 (lower, upper 함수)
- 파이썬스럽게 코딩하기, PEP8 가이드 정리
- numpy.arange(), 균일 간격 배열
- numpy.concatenate(), 배열 합치기
- numpy hstack, vstack 함수 (배열 연결)
- numpy.average(), 배열 가중 평균
- Numpy 배열을 List로 변환
- 파이썬 List를 Numpy 배열로 변환
- numpy flatten() 함수, 1차원 배열로 변환(평탄화)
- numpy.log(), 로그 함수 사용 방법