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

Nir*_*Nir 6 python sorting string

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

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

>>> 'a' > '1'
True
>>> 'a' > 1
True
Run Code Online (Sandbox Code Playgroud)

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

例:

未排序列表:

['big', 'apple', '42nd street', '25th of May', 'subway']
Run Code Online (Sandbox Code Playgroud)

Python的默认排序:

['25th of May', '42nd street', 'apple', 'big', 'subway']
Run Code Online (Sandbox Code Playgroud)

要求排序:

['apple', 'big', 'subway', '25th of May', '42nd street']
Run Code Online (Sandbox Code Playgroud)

grc*_*grc 11

>>> 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']
Run Code Online (Sandbox Code Playgroud)

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

你可以阅读更多有关排序在这里.

  • 这正是OP所要求的.值得指出的是,这不会做[自然排序](http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort)字符串数字,`'2'`将在''11'之后列出. (5认同)