gpt4 book ai didi

python - 如何按字符串长度后跟字母顺序对列表进行排序?

转载 作者:IT老高 更新时间:2023-10-28 20:21:31 31 4
gpt4 key购买 nike

Given a list of words, return a list with the same words in order oflength (longest to shortest), the second sort criteria should bealphabetical. 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

它按长度排序,但我不知道如何将第二个条件应用于此排序,即按字母降序。

最佳答案

您可以分两步完成:

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

Python 的排序是稳定的,这意味着当长度相等时,按长度对列表进行排序会使元素按字母顺序排列。

你也可以这样做:

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

通常你永远不需要 cmp,它甚至在 Python3 中被删除了。 key 更容易使用。

关于python - 如何按字符串长度后跟字母顺序对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4659524/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com