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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.