cmp_to_keyの実装
比較対象の2つの値を引数として、第一引数が第二引数よりも小さければ負の値、大きければ正の値、等しければ0を返すように実装します。
from functools import cmp_to_key def compare(arg1, arg2): #数値を昇順ソート if arg1 == arg2: return 0 if arg1 < arg2: return -1 if arg1 > arg2: return 1 ls=[3,0,2,1] ls = sorted(ls, key=cmp_to_key(compare)) print(ls)
例題
参考サイト
functools — Higher-order functions and operations on callable objects — Python 3.11.4 documentation