파이썬에서 정렬하는 두 가지 방법
리스트를 정렬하는 내장함수. 기존의 리스트를 정렬함.
key
reverse
사용 예시
list = [3, 5, 1, 4, 2]
list.sort() # [1, 2, 3, 4, 5]
list.sort(reverse=True) # [5, 4, 3, 2, 1]
list = [('this', 4), ('is', 2), ('sort', 3), ('function', 1)]
list.sort(key=lambda x:x[1]) # [('function', 1), ('is', 2), ('sort', 3), ('this', 4)]
iterabe한 데이터의 정렬 내장함수. 정렬된 새로운 리스트를 반환.
리스트 뿐만 아니라 튜플, set, string 을 정렬할 수 있음.
iterable
key
reverse
사용 예시
list = [3, 5, 1, 4, 2]
sorted_list = sorted(list)
print(sorted_list) # [1, 2, 3, 4, 5]
reversed_list = sorted(list, reverse=True)
print(reversed_list) # [5, 4, 3, 2, 1]
list = [('this', 4), ('is', 2), ('sort', 3), ('function', 1)]
key_sorted_list = sorted(list, key=lambda x:x[1])
print(key_sorted_list) # [('function', 1), ('is', 2), ('sort', 3), ('this', 4)]