squirrel2300

导航

python3 sort

#https://docs.python.org/3.5/howto/sorting.html?highlight=sort

#In Python 3.2, the functools.cmp_to_key() function was added to the functools module in the standard library

 

 

# compare function

def mycmp(x,y):
    if len(x) == len(y):
        if x== y :
            return 0
        elif x < y:
            return -1
        else:
            return 1
    else:
        return len(x) - len(y)

#transfer compare func to key
def cmp_to_key(mycmp):
    '''Convert a cmp= function into a key= function'''
    class K(object):
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K

#first do unique
line_list = list(np.unique(line_list))

#sort the string list
res = line_list.sort(key = cmp_to_key(mycmp))

posted on 2017-04-15 23:22  squirrel2300  阅读(145)  评论(0编辑  收藏  举报