我有一个要排序的字符串列表。
默认情况下,字母的值比数字(或字符串数字)大,这使它们在排序列表中排在最后。
>>> '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的sort函数带有一个可选key
参数,允许您指定在排序之前应用的函数。元组按第一个元素排序,然后按第二个元素排序,依此类推。
您可以在此处阅读有关排序的更多信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句