Language/Python

Python - 정렬 내장함수

둉이 2021. 6. 27. 18:31

 

sorted 함수

: 문자열, 리스트, 딕셔너리 등 정렬 가능

  결과는 리스트 자료형으로 반환

# 문자열 정렬
sorted("hello world")  # [' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
# 리스트 정렬
sorted([i for i in range(1,10,2)])  # [1, 3, 5, 7, 9]
# 튜플 정렬
sorted({3,2,1})  # [1, 2, 3]
# 셋 정렬
sorted((3,2,1))  # [1, 2, 3]
# 딕셔너리 정렬
sorted({'a':10,'b':2,'c':6})  # ['a', 'b', 'c']

- 내림차순

sorted(리스트명, reverse = True)

- sort()와의 차이점

1. sort()는 None 반환, sorted()는 리스트 반환

  → sort()는 원본 리스트를 건드리지 않음

lst.sort()
lst = sorted(lst)

2. sort()는 리스트에만 사용 가능

 

리스트 정렬

: sort(), sorted()

 

 

 딕셔너리 정렬

- key값 기준 정렬

ndict = {10:1, 1:1, 2:2}
ndict = sorted(ndict.items())  # [(1, 1), (2, 2), (10, 1)]
ndict = sorted(ndict.items(), reverse = True)  # [(10, 1), (2, 2), (1, 1)]

- value값 기준 정렬

ndict = {10:1, 1:1, 2:2}
ndict = sorted(ndict.items(), key = lambda x:x[1])  # [(2, 2), (10, 1), (1, 1)]