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

后端 未结 5 604
迷失自我
迷失自我 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:33

    First sort by Alphabet and then sort by Length.

    Here is a working example

    mylist.sort()
    mylist = sorted(mylist, key=len, reverse=False)
    
    # Print the items on individual line
    for i in mylist:
        print(i)
    
    0 讨论(0)
  • 2020-11-27 15:42

    You can do it in two steps like this:

    the_list.sort() # sorts normally by alphabetical order
    the_list.sort(key=len, reverse=True) # sorts by descending length
    

    Python's sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.

    You can also do it like this:

    the_list.sort(key=lambda item: (-len(item), item))
    

    Generally you never need cmp, it was even removed in Python3. key is much easier to use.

    0 讨论(0)
  • 2020-11-27 15:47
    n = ['aaa', 'bbb', 'ccc', 'ffffdd', 'ffffdl', 'yyyyy']
    
    for i in reversed(sorted(n, key=len)):
        print i
    

    yyyyy ffffdl ffffdd ccc bbb aaa

    for i in sorted(n, key=len, reverse=True):
         print i
    

    yyyyy ffffdd ffffdl aaa bbb ccc

    0 讨论(0)
  • 2020-11-27 15:55
    -Sort your list by alpha order, then by length.
    
    See the following exmple:
    
    >>> coursesList = ["chemistry","physics","mathematics","art"]
    >>> sorted(coursesList,key=len)
    ['art', 'physics', 'chemistry', 'mathematics']
    >>> coursesList.append("mopsosa")
    >>> sorted(coursesList,key=len)
    ['art', 'physics', 'mopsosa', 'chemistry', 'mathematics']
    >>> coursesList.sort()
    >>> sorted(coursesList,key=len)
    ['art', 'mopsosa', 'physics', 'chemistry', 'mathematics']
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题