how to sort by length of string followed by alphabetical order?

后端 未结 5 632
迷失自我
迷失自我 2020-11-27 15:24

I\'m currently new to python and got stuck at this question, can\'t seem to find the proper answer.

question:Given a list of words, return a list with the same words

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 15:57

    Although Jochen Ritzel said you don't need cmp, this is actually a great use case for it! Using cmp you can sort by length and then alphabetically at the same time in half the time sorting twice would take!

    def cmp_func(a, b):
        # sort by length and then alphabetically in lowercase
        if len(a) == len(b):
            return cmp(a, b)
        return cmp(len(a), len(b))
    
    sorted_the_way_you_want = sorted(the_list, cmp=cmp_func)
    

    Example:

    >>> the_list = ['B', 'BB', 'AA', 'A', 'Z', 'C', 'D']
    >>> sorted(the_list, cmp=cmp_func)
    ['A', 'B', 'C', 'D', 'Z', 'AA', 'BB']
    

    Note, if your list is a mix of upper and lower case replace cmp(a, b) with cmp(a.lower(), b.lower()) as python sorts 'a' > 'Z'.

    In python3 you'd need to be sorting objects with __lt__ style comparison functions defined or functools.cmp_to_key() which does that for you.

提交回复
热议问题