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

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

提交回复
热议问题