按长度和字母顺序对字符串列表进行排序

编程入门 行业动态 更新时间:2024-10-27 02:18:38
本文介绍了按长度和字母顺序对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

示例列表:

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']

更多推荐

按长度和字母顺序对字符串列表进行排序

本文发布于:2023-10-18 03:25:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502940.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字母   顺序   长度   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!