-
파이썬 정렬Python/이것저것 파이썬 2022. 12. 31. 20:56반응형
기본
print(sorted([5, 2, 3, 1, 4])) # [1, 2, 3, 4, 5]
print(sorted([5, 2, 3, 1, 4], reverse=True)) # [5, 4, 3, 2, 1]
a = [5, 2, 3, 1, 4] a.sort() print(a) # [1, 2, 3, 4, 5]
print(sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})) # [1, 2, 3, 4, 5]
키
student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] print(sorted(student_tuples, key=lambda student: student[2])) # sort by age # [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
operator.itemgetter를 사용하는 것이 더 빠르다.
from operator import itemgetter student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] print(sorted(student_tuples, key=itemgetter(2))) # sort by age
다중 정렬
from operator import itemgetter student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] print(sorted(student_tuples, key=itemgetter(1, 2))) # sort by grade, age # [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
복잡한 정렬
크다면 1, 같다면 0, 작다면 -1을 리턴
from functools import cmp_to_key def compare(a, b): return int(b + a) - int(a + b) nums = ['6', '10', '2'] print(sorted(nums, key=cmp_to_key(compare))) # ['6', '2', '10']
반응형