Python的排序列表 [英] Python Sort List

查看:135
本文介绍了Python的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前Python和很新的这门语言。

I'm currently python and quite new to this language.

排序列表基于两CriteriaGiven单词列表,返回顺序长度与同一字的列表(最长至最短),第二类标准应该是按字母顺序排列。提示:你需要想到两个功能

Sort List Based on Two CriteriaGiven 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.

谁能帮助我?

推荐答案

您只需要一个电话,以排序,因为Python会自动按字典顺序排序的元组。也就是说,如果你问的Python他们的第一个元素来比较两个元组将责令他们,除非那些比较平等在这种情况下它会命令他们通过自己的第二个要素,但如果这些比较平等在这种情况下...

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...

您想要减去其长度的元素,然后在列表中按字母顺序排列,所以你想一个字符串取值是元组( - LEN(S),S)。因此:

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

这篇关于Python的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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