简体   繁体   English

Python:如何根据尾随数字对字符串进行排序?

[英]Python: How to sort strings with regards to their trailing numbers?

What is the best way to sort a list of strings with trailing digits用尾随数字对字符串列表进行排序的最佳方法是什么

>>> list = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']
>>> list.sort()
>>> print list
['mba23m1', 'mba23m124', 'mba23m23', 'mba23m5']

is there a way to have them sorted as有没有办法让它们排序为

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']

you can use natsort library.你可以使用 natsort 库。

from natsort import natsorted # pip install natsort
list = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']

output: output:

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']

Use a lambda (anonymous) function and sort() 's key argument:使用 lambda (匿名) function 和sort()key参数:

ls = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']
ls.sort(key=lambda x: int(x.split('m')[-1]))
print(ls)

Yielding:产量:

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']
  1. Create a function to remove trailing digits and return other part of the string.创建一个 function 以删除尾随数字并返回字符串的其他部分。 (Lets consider this function as f_remove_trailing_digits(s) ) (让我们将此 function 视为 f_remove_trailing_digits(s) )

    def f_remove_trailing_digits(s): return s.rstrip("0123456789") def f_remove_trailing_digits(s): return s.rstrip("0123456789")

  2. Then you can sort using this way然后你可以使用这种方式排序

    list.sort(key=lambda x:f_remove_trailing_digits(x)) list.sort(key=lambda x:f_remove_trailing_digits(x))

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

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