파이썬에서 정렬하는 방법에는 2가지가 있다.
sort() 함수와 sorted() 함수
<list>.sort([key = <function>], [reverse = True|False])
a = [5, 2, 3, 1, 4]
a.sort() # sort 함수로 정렬
print(a)
sorted(정렬할 데이터, [key = <function>], [reverse = True|False])
a = [5, 2, 3, 1, 4]
print(sorted(a)) # sorted 함수로 정렬
# [1, 2, 3, 4, 5]
print(a) # sorted 함수는 기존 리스트에 영향을 주지 않음
# [5, 2, 3, 1, 4]
student_tuples = [
# name, grade, age
('john', 'A', 15),
('tony', 'B', 12),
('dave', 'C', 10),
('happy', 'A', 12)
]
print(sorted(student_tuples)) # key 값이 없을 경우, 가장 첫 번째를 기준으로 정렬
# [('dave', 'C', 10), ('happy', 'A', 12), ('john', 'A', 15), ('tony', 'B', 12)]
print(sorted(student_tuples, key=lambda x: x[2])) # x[2] 즉, age를 기준으로 오름차순 정렬
# [('dave', 'C', 10), ('tony', 'B', 12), ('happy', 'A', 12), ('john', 'A', 15)]
## 특정 key값을 기준으로 내림차순으로 정렬할 경우
## 원소 앞에 마이너스 부호(-) 를 붙이면 내림차순 정렬
print(sorted(student_tuples, key=lambda x: -x[2])) # x[2] 즉, age를 기준으로 내림차순 정렬
# [('john', 'A', 15), ('tony', 'B', 12), ('happy', 'A', 12), ('dave', 'C', 10)]
## key 가 여러개일 경우
## 튜플 형식으로 람다식을 세워서 정렬한다.
print(sorted(student_tuples, key=lambda x: (x[2], x[1]))) # x[2](age), x[1](grade) 순으로 오름차순 정렬
# [('dave', 'C', 10), ('happy', 'A', 12), ('tony', 'B', 12), ('john', 'A', 15)]
## age순으로 내림차순 정렬, grade 순으로 오름차순 정렬
print(sorted(student_tuples, key=lambda x: (-x[2], x[1])))
# [('john', 'A', 15), ('happy', 'A', 12), ('tony', 'B', 12), ('dave', 'C', 10)]
from operator import itemgetter, attrgetter
student_tuples = [
# name, grade, age
('john', 'A', 15),
('tony', 'B', 12),
('dave', 'C', 10),
('happy', 'A', 12)
]
print(sorted(student_tuples, key=itemgetter(1))) # grade를 기준으로 오름차순 정렬
# [('john', 'A', 15), ('happy', 'A', 12), ('tony', 'B', 12), ('dave', 'C', 10)]
a = ["b", "e", "a", "d", "c", "f"]
print(sorted(a, reverse=True))
# ['f', 'e', 'd', 'c', 'b', 'a']
a.sort(reverse=True)
print(a)
# ['f', 'e', 'd', 'c', 'b', 'a']
string = "beadcf"
sorted_s =sorted(string) # sorted 함수로 문자열 정렬
print(sorted_s)
# ['a', 'b', 'c', 'd', 'e', 'f']
print("".join(sorted_s))
# abcdef