[英]how to sort a list based on a specific keywords in the string
i have this list below我在下面有这个列表
my_list = ['STNNC-A11-SD03', 'STNNC-BDD-SD01', 'STNNC-BDD-SD04', 'STNNC-BDB-SD02']
i tried below method and this is what it returned which is expected since its sorting from left to right:我尝试了下面的方法,这是它返回的预期结果,因为它从左到右排序:
my_list.sort()
print(my_list)
['STNNC-A11-SD03', 'STNNC-BDB-SD02', 'STNNC-BDD-SD01', 'STNNC-BDD-SD04']
but below is the output i am looking for但下面是我正在寻找的输出
['STNNC-BDD-SD01', 'STNNC-BDB-SD02', 'STNNC-A11-SD03', 'STNNC-BDD-SD04']
is there anyway that i can sort the list based the last numerical section?无论如何,我可以根据最后一个数字部分对列表进行排序吗?
Thanks so much.非常感谢。
You can use sorted()
and extrcat the number from string use the number as key in sorted
您可以使用sorted()
并从字符串中提取数字使用数字作为sorted
res = sorted(my_list, key=lambda x: int(x.split('-SD')[-1]))
print(res)
Output:输出:
['STNNC-BDD-SD01', 'STNNC-BDB-SD02', 'STNNC-A11-SD03', 'STNNC-BDD-SD04']
If you just want to sort based on the third component of each string, you can use:如果您只想根据每个字符串的第三个组件进行排序,可以使用:
my_list.sort(key=lambda s: s.split("-")[2])
This produces:这产生:
['STNNC-BDD-SD01', 'STNNC-BDB-SD02', 'STNNC-A11-SD03', 'STNNC-BDD-SD04']
#you can try this, I hope you will get you solution. #你可以试试这个,我希望你能得到你的解决方案。
my_list = ['STNNC-A11-SD03', 'STNNC-BDD-SD01', 'STNNC-BDD-SD04', 'STNNC-BDB-SD02']
base_list = []
for i in my_list:
base_list.append(int(i[-2:]))
zipped_lists = zip(base_list, my_list)
sorted_zipped_lists = sorted(zipped_lists)
sorted_list = [element for _, element in sorted_zipped_lists]
print(sorted_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.