繁体   English   中英

排序字符串列表并在python中的字母后面放置数字

[英]Sort list of strings and place numbers after letters in python

我有一个我要排序的字符串列表。

默认情况下,字母的值大于数字(或字符串数​​字),这将它们放在排序列表中。

>>> 'a' > '1'
True
>>> 'a' > 1
True

我希望能够将所有以数字开头的字符串放在列表的底部。

例:

未排序列表:

['big', 'apple', '42nd street', '25th of May', 'subway']

Python的默认排序:

['25th of May', '42nd street', 'apple', 'big', 'subway']

要求排序:

['apple', 'big', 'subway', '25th of May', '42nd street']
>>> a = ['big', 'apple', '42nd street', '25th of May', 'subway']
>>> sorted(a, key=lambda x: (x[0].isdigit(), x))
['apple', 'big', 'subway', '25th of May', '42nd street']

Python的排序函数采用可选的key参数,允许您指定在排序之前应用的函数。 元组按其第一个元素排序,然后按第二个元素排序,依此类推。

您可以在此处阅读有关排序的更多信

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM