2012年9月20日 星期四

Sort List With Custom Comparator In Python

def asc_comparator(a, b):
    return a - b


def desc_comparator(a, b):
    return b - a

my_list = [8, 1, 3]
my_list.sort(asc_comparator)
>> [1, 3, 8]

my_list.sort(desc_comparator)
>> [8, 3, 1]

如果a, b是兩個物件也可以自訂comparator去取出要比的東西出來。
comparator 回傳值必須是 int
此為比較日期時因為我用 timedelta.total_seconds() 才注意到的