簡體   English   中英

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

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

我有一個我要排序的字符串列表。

默認情況下,字母的值大於數字(或字符串數​​字),這將它們放在排序列表中。

>>> '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的排序函數采用可選的key參數,允許您指定在排序之前應用的函數。 元組按其第一個元素排序,然后按第二個元素排序,依此類推。

您可以在此處閱讀有關排序的更多信

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM