sorted(정렬할 데이터)
sorted(정렬할 데이터, reverse 파라미터)
sorted(정렬할 데이터, key 파라미터)
sorted(정렬할 데이터, key 파라미터, reverse 파라미터)
첫 번째 파라미터(정렬할 데이터)
들어온 iterable 데이터를 새로운 정렬된 리스트로 만들어서 반환
- key 파라미터
key 값을 기준으로 비교를 하여 정렬
sorted( ~ , key= ~)로 입력하게 되면 해당 키를 기준으로 정렬하여 반환합니다.
- reverse 파라미터
오름차순/내림차순
기본값으로 reverse=False (오름차순으로 정렬)
sorted( ~ , reverse=True) (내림차순으로 정렬)
+ 리스트.sort()와 차이
리스트.sort() 는 본래 리스트를 변환하여 정렬. 리스트를 반환하지 X
sorted(리스트) 는 본래 리스트와 다른 정렬한 새로운 리스트를 반환
예제
import operator
dic = {'b': 400, 'f': 300, 'a': 200, 'd': 100, 'c': 500}
temp1 = sorted(dic.items())
print(temp1)
#[('a', 200), ('b', 400), ('c', 500), ('d', 100), ('f', 300)]
#operator 모듈의 itemgetter 함수로 dictionary 의 value 값에 접근 그 기준으로 역정렬
temp2 = sorted(dic.items(), key=operator.itemgetter(1). reverse=True)
print(temp2)
#[('c', 500), ('b', 400), ('f', 300), ('a', 200), ('d', 100)]
#lambda 이용 dictionary value 역정렬
temp3 = sorted(d.items(), key=lambda x: x[1], reverse=True)
print(temp3)
#[('c', 500), ('b', 400), ('f', 300), ('a', 200), ('d', 100)]
'코테 공부 > python' 카테고리의 다른 글
Python math.factorial(n) math.comb(n, r) (0) | 2023.05.30 |
---|---|
Python map (0) | 2023.05.30 |
Python 유니코드 관련 ord('a') #97, chr(97) #a (0) | 2023.05.29 |
Python 각도기 문제 우와 (0) | 2023.05.29 |
Python .split() (empty seperator 불가) (0) | 2023.05.28 |