我有一个字符串列表,我想对其进行排序。
默认情况下,字母的值大于数字(或字符串数字),这将字母放在排序列表的最后。
>>> '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']
发布于 2014-07-08 06:02:10
>>> 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
参数,允许您指定在排序之前应用的函数。元组按第一个元素排序,然后按第二个元素排序,依此类推。
您可以阅读更多关于排序这里的内容。
https://stackoverflow.com/questions/24624644
复制相似问题