按长度排序的列表,但在一个步骤中按字母顺序排列的长度相同 [英] Length-wise-sorted list but, same length in alphabetical-order in a step

查看:52
本文介绍了按长度排序的列表,但在一个步骤中按字母顺序排列的长度相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Python 字符串列表类似于 x 但足够长:

x = ['aaa','ab','aa','c','a','b','ba']

我想将此列表排序为:['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa'] 我做到了如下两步:

<预><代码>>>>x.sort()>>>x.sort(key=len)>>>X['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa']

但我需要一步:我还使用了 lambda 函数(<强>接受帮助):

<预><代码>>>>x.sort(key=lambda item: (item, len(item)))>>>X['a', 'aa', 'aaa', 'ab', 'b', 'ba', 'c']

但不是我想要的:

可以一步到位吗?让我开心.

我的 Python:

~$ python --version蟒蛇 2.6.6

解决方案

你把元组的顺序弄错了.当 Python 对元组进行排序时,第一个值是 main 排序,第二个是子排序,等等...... - 你的代码假定相反的顺序.

您想按长度排序,然后按字母顺序:

<预><代码>>>>x.sort(key=lambda item: (len(item), item))>>>X['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa']

正如 DSM 在评论中指出的那样,Python 首先将字母排序为大写,然后是小写.如果不需要这种行为,请参阅此答案.

My Python List of string is something like x but long enough:

x = ['aaa','ab','aa','c','a','b','ba']      

I wants to sort this list as: ['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa'] and I did as follows in two steps:

>>> x.sort()   
>>> x.sort(key=len)      
>>> x
['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa']   

But I need in one-step: I also tied using lambda function (taken help):

>>> x.sort(key=lambda item: (item, len(item)))
>>> x
['a', 'aa', 'aaa', 'ab', 'b', 'ba', 'c']  

But not as I desired:

Is it possible in one-step? Please me.

My Python:

~$ python --version  
Python 2.6.6

解决方案

You got the order of the tuple the wrong way round. When Python sorts on tuples, the first value is the main sort, with the second being the subsort, etc... - your code presumes the opposite order.

You want to sort by length, then alphabetically:

>>> x.sort(key=lambda item: (len(item), item))
>>> x
['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa']

Edit: As DSM points out in the comments, Python sorts letters as capitals first, then lowercase. If this behaviour isn't wanted, see this answer.

这篇关于按长度排序的列表,但在一个步骤中按字母顺序排列的长度相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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