sort와sorted의 차이점에 대해 알아보자.
- 1. sort()
- 기존 리스트를 정렬
- 반환 값을 가지지 않는다
list_a = [4,3,1,2]
list_a.sort() # 반환값 없이 list_a 정렬
print(list_a) # sort에 의해 정렬된 list_a
## sort()는 반환값을 가지지 않으므로 변수에 할당하여도 아무것도 할당되지 않는다
aa = list_a.sort() # None
- 2. sorted()
- 기존의 리스트를 유지하면서 정렬된값을 새로 반환
a = [4,2,1,3]
print(sorted(a)) # [1,2,3,4]
print(a) # [4,2,1,3] # 기존 리스트값은 변경되지 않음
# 변수에 할당
aa = sorted(a)
print(aa) # [1,2,3,4]
-
key parameter
- sorted와 sort 모두 비교를 위한 key 파라미터를 가짐
- 함수여야함
student_tuples = [ # [()]
('aohn', 'A', 15),
('cane', 'B', 12),
('bave', 'B', 10),
]
# default
sorted(student_tuples) # 맨처음 요소 기준으로 정렬
# 결과
# [('aohn', 'A', 15), ('bave', 'B', 10), ('cane', 'B', 12)]
# change key
# 정렬할 리스트의 3번째 요소를 기준 (리스트 내 튜플3번째 요소)
sorted(student_tuples, key=lambda student: student[2])
# 결과
#[('bave', 'B', 10), ('cane', 'B', 12), ('aohn', 'A', 15)]
'Python > 그때 이걸 알았더라면..' 카테고리의 다른 글
[Python] 리스트 내 리스트들 합치기 (0) | 2020.04.09 |
---|---|
[Pandas] Insert 활용하기 (0) | 2020.04.09 |
[Pandas] apply 사용 시 index 활용 꿀팁 (0) | 2020.03.28 |
[Pandas] Groupby 와 unstack 활용 (0) | 2020.02.26 |
[Pandas] map을 활용하여 DataFrame & Series Data Handling (0) | 2020.02.26 |