[Python3] functools.cmp_to_key 특정 기준으로 정렬하기

CHANGMIN LEE·2021년 9월 14일
0
from functools import cmp_to_key

def custom_key(A, B):
    if A > B:
        return 1
    else:
        return -1
      
tmp = [5,4,3,2,1]
tmp.sort(key=cmp_to_key(custom_key))

print(tmp)

A, B 를 비교해서

입력받은 순서가 바뀌어야 하는 경우에는 (양수)를 반환
순서가 유지되는 경우에는 (음수)를 반환하는 방식으로 코드를 작성하면

특정한 조건을 가지고 정렬이 가능하다.

profile
Beer Beard Beer

0개의 댓글