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参数,允许您指定在排序之前应用的函数.元组按其第一个元素排序,然后按第二个元素排序,依此类推.
你可以阅读更多有关排序在这里.
| 归档时间: |
|
| 查看次数: |
2541 次 |
| 最近记录: |