如何按字符串长度和字母顺序排序? [英] how to sort by length of string followed by alphabetical order?

查看:108
本文介绍了如何按字符串长度和字母顺序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前是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.

这是我到目前为止所拥有的:

This is what I have so far:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆