[파이썬(Python)]- Sorted

배병진·2023년 7월 11일
0

개인공부-Python

목록 보기
15/22

sorted

  • 매개변수로 들어온 이터러블한 데이터를 새로운 정렬된 리스트로 만들어서 반환해주는 함수

사용법

  • sorted(정렬할 데이터)
  • sorted(정렬할 데이터, reverse 파라미터)
  • sorted(정렬할 데이터, key 파라미터)
  • sorted(정렬할 데이터, key 파라미터, reverse 파라미터)

정렬할 데이터에는 이터러블한 데이터이어야 한다.

Key 파라미터

  • 어떤 것을 기준으로 정렬할 것인가에 대한 기준
  • key 값을 기준으로 정렬

reverse 옵션

  • 해당 파라미터를 오름차순으로 정렬할지, 내림차순으로 정렬할지 결정
  • reverse=False > 오름차순(default)
  • reverse=True > 내림차순

리스트.sort(), sorted(리스트)의 차이

  • 리스트.sort()는 원본을 정렬해 변환
  • sorted(리스트)는 원본을 두고 정렬한 새로운 리스트를 반환하는 것

리스트 정렬

a=[11,5,111,1,13,50,22]
b= sorted(a)
c= sorted(a, reverse=True)

print(f'sorted.list(a)={a}')
print(f'sorted(a)={b}')
print(f'reverse.sorted(a)={c}')

>>>
sorted.list(a)=[11, 5, 111, 1, 13, 50, 22]
sorted(a)=[1, 5, 11, 13, 22, 50, 111]
reverse.sorted(a)=[111, 50, 22, 13, 11, 5, 1]

딕셔너리 key 정렬

a = dict()
a['a'] = 1
a['c'] = 3
a['b'] = 2
a['e'] = 5
a['f'] = 6
a['d'] = 4
a['g'] = 7

print("\n1. basic dict")
print(a)

#오름차순 dict
print("\n2. basic dict, asc")
f = sorted(a.items())
print(f)

#내림차순 dict
print("\n3. basic dict, desc")
g=sorted(a.items(), reverse=True) // 튜플형 반환
print(g)

#키만 정렬 및 출력
print("\n4. only key print")
h=sorted(a.keys())
print(h)

#키만 정렬 및 출력2
print("\n5. only key print")
i=sorted(a)
print(i)

>>>
1. basic dict
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'f': 6, 'd': 4, 'g': 7}

2. basic dict, asc
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]

3. basic dict, desc
[('g', 7), ('f', 6), ('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]

4. only key print
['a', 'b', 'c', 'd', 'e', 'f', 'g']

5. only key print
['a', 'b', 'c', 'd', 'e', 'f', 'g']

operator 모듈

  • 파이썬의 내장 연산자에 해당하는 효율적인 함수 집합을 사용하게 해준다.

operator를 이용하여 value기준을 sorted하기 위한 방법

  • sorted(딕셔너리.items(), key=operator.itemgetter(1))

operator모듈 value 정렬

import operator

a = {'a':5,'b':2,'c':1,'d':3,'e':9,}

print("\n1. basic dict")
print(a.items())

print("\n2. basic dict, asc")
b = sorted(a.items())
print(b)

print("\n3. used operator sorted")
c = sorted(a.items(), key=operator.itemgetter(1))
print(c)

print("\n4. used operator, reverse=True")
d = sorted(a.items(), key=operator.itemgetter(1), reverse=True)
print(d)
  
>>>
1. basic dict
dict_items([('a', 5), ('b', 2), ('c', 1), ('d', 3), ('e', 9)])

2. basic dict, asc
[('a', 5), ('b', 2), ('c', 1), ('d', 3), ('e', 9)]

3. used operator sorted
[('c', 1), ('b', 2), ('d', 3), ('a', 5), ('e', 9)]

4. used operator, reverse=True
[('e', 9), ('a', 5), ('d', 3), ('b', 2), ('c', 1)]

lambda이용한 value 정렬

  • sorted(딕셔너리.items(), key=lambda x: x[1])
  • key를 x로 셋, 다른 문자로 세팅을 하여도 무방
import operator

a = {'a':5,'b':2,'c':1,'d':3,'e':9,}

print('\n1.origin dict')
print(a.items())

print('\n2. dict : sorted(a.items())')
b = sorted(a.items())
print(b)

print('\n3. dict : sorted(a.items(), key=lambda x: x[1])')
c= sorted(a.items(), key=lambda x: x[1])
print(c)

print('\n4. dict : sorted(a.items(), key=lambda x: x[1], reverse=True')
d=sorted(a.items(), key=lambda x: x[1], reverse=True)
print(d)
  
>>>
1.origin dict
dict_items([('a', 5), ('b', 2), ('c', 1), ('d', 3), ('e', 9)])

2. dict : sorted(a.items())
[('a', 5), ('b', 2), ('c', 1), ('d', 3), ('e', 9)]

3. dict : sorted(a.items(), key=lambda x: x[1])
[('c', 1), ('b', 2), ('d', 3), ('a', 5), ('e', 9)]

4. dict : sorted(a.items(), key=lambda x: x[1], reverse=True
[('e', 9), ('a', 5), ('d', 3), ('b', 2), ('c', 1)]
profile
history and study

0개의 댓글