按长度和字母顺序对字符串列表进行排序 [英] Sort list of strings by length and alphabetically

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

问题描述

我需要根据给定的两个标准对单词列表进行排序.我需要按长度顺序(从最长到最短)返回具有相同单词的列表,第二个排序条件应为字母顺序.

示例列表:

  l = ['aa','aaa','aaaa','b','bb','z','ccc'] 

所需的输出:

  ['aaaa','aaa','ccc','aa','bb','b','z'] 

解决方案

您只需调用一次 sort ,因为Python会自动按字典顺序对元组进行排序.也就是说,如果您要求Python比较两个元组,则将按它们的第一个元素对其进行排序,除非在这种情况下两者比较相等,否则将按其第二个元素对其进行排序,除非在这种情况下它们将进行比较...

您要按照元素的长度减去其长度,然后按字母顺序对元素列表进行排序,因此您希望字符串 s 的键为元组(-len(s),s).因此:

 >>>l = ['aa','aaa','aaaa','b','bb','z','ccc']>>>sort_key = lambda s:(-len(s),s)>>>l.sort(key = sort_key)>>>升['aaaa','aaa','ccc','aa','bb','b','z'] 

I need to sort a list of words based on two criteria given. I need to return a list with the same words in order of length (longest to shortest) and the second sort criteria should be alphabetical.

Example list :

l = ['aa','aaa','aaaa','b','bb','z','ccc']

Desired output:

['aaaa', 'aaa', 'ccc', 'aa', 'bb', 'b', 'z']

解决方案

You only need one call to sort, because Python automatically sorts tuples lexicographically. That is, if you ask Python to compare two tuples it will order them by their first element, except if those compare equal in which case it will order them by their second element, except if those compare equal in which case...

You want to sort the list of elements by minus their length and then alphabetically, so you want the key of a string s to be the tuple (-len(s), s). Hence:

>>> l = ['aa','aaa','aaaa','b','bb','z','ccc']
>>> sort_key = lambda s: (-len(s), s)
>>> l.sort(key=sort_key)
>>> l
['aaaa', 'aaa', 'ccc', 'aa', 'bb', 'b', 'z']

这篇关于按长度和字母顺序对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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