如何按字符串的长度和字母顺序排序? [英] how to sort by length of string followed by alphabetical order?
问题描述
我目前是 python 的新手,被这个问题困住了,似乎找不到正确的答案.
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 in order of length (longest to shortest), the second sort criteria should be alphabetical. Hint: you need think of two functions.
这是我目前所拥有的:
def bylength(word1,word2):
return len(word2)-len(word1)
def sortlist(a):
a.sort(cmp=bylength)
return a
它按长度排序,但我不知道如何将第二个条件应用于这种排序,即按字母降序.
it sorts by length but I don't know how to apply the second criteria to this sort, which is by alphabetical descending.
推荐答案
你可以像这样分两步完成:
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 的排序是稳定的,这意味着按长度对列表进行排序,当长度相等时,元素会按字母顺序排列.
Python's sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.
你也可以这样做:
the_list.sort(key=lambda item: (-len(item), item))
通常你永远不需要cmp
,它甚至在Python3中被删除了.key
更容易使用.
Generally you never need cmp
, it was even removed in Python3. key
is much easier to use.
这篇关于如何按字符串的长度和字母顺序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!