首页 > 解决方案 > 用里面的字符串对列表进行排序

问题描述

我再次需要你的帮助,我想整理一份清单。排序是根据A或B前面的数字

怎么做?谢谢


original list:

['1A21','1B21','21A21','21B21','14A21','14B21'....]

the length of string with A and B are not the same. For example, there are '31A21', but there is no '31B21'

sorted list:
['1A21','2A21'........'1B21','2B21'.......]


My original code is for the case only has either A or B inside the string:

wells.sort(key=key_sortwell,reverse=True) 

def key_sortwell(well):
      return int(well.split('A')[0])

But now I have both A and B inside the string. Now I am not sure how to do it? 


标签: python

解决方案


您可以将内置sorted函数与一个键函数一起使用,该函数接受每个字符串并返回之前的数字AB

sorted_lst = sorted(original_lst, key=lambda s:s.replace('B', 'A').split('A')[0])

推荐阅读