정렬할 데이터에는 이터러블한 데이터이어야 한다.
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]
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']
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)]
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)]