简体   繁体   English

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

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

I have a list of strings that I want to sort. 我有一个我要排序的字符串列表。

By default, letters have a larger value than numbers (or string numbers), which places them last in a sorted list. 默认情况下,字母的值大于数字(或字符串数​​字),这将它们放在排序列表中。

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

I want to be able to place all the strings that begins with a number at the bottom of the list. 我希望能够将所有以数字开头的字符串放在列表的底部。

Example: 例:

Unsorted list: 未排序列表:

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

Python's default sorting: Python的默认排序:

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

Requested sorting: 要求排序:

['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's sort functions take an optional key parameter, allowing you to specify a function that gets applied before sorting. Python的排序函数采用可选的key参数,允许您指定在排序之前应用的函数。 Tuples are sorted by their first element, and then their second, and so on. 元组按其第一个元素排序,然后按第二个元素排序,依此类推。

You can read more about sorting here . 您可以在此处阅读有关排序的更多信

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

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