본문 바로가기

Application-level프로그래밍

[Python] Custom Sorting

참고:

http://code.google.com/edu/languages/google-python-class/sorting.html



a=[1,5,4,2]

print sorted(a)

print sorted(a, reverse=True)

print a


def KeyFunc(e):

    return abs(e-3.6) # distance to 3.6

    

print sorted(a,key=KeyFunc) # [4,5,2,1]



b=[ (2,3), (9,2), (1,5), (0,10) ]

print b[2][0] # 1 in (1,5)

print b[2][1] # 5 in (1,5)


def CmpFunc(a,b):

    if (a[0]+a[1]) < (b[0]+b[1]):

        return -1

    elif (a[0]+a[1]) == (b[0]+b[1]):

        return 0

    else: 

        return 1


CmpFunc(b[1],b[0]) # 1

print sorted(b, cmp=CmpFunc) #[(2, 3), (1, 5), (0, 10), (9, 2)]