I am trying to sort a python list using sorted method as per the code below. However the sorting is not happening properly.
#sort using the number part of the string
mylist = ['XYZ-78.txt', 'XYZ-8.txt', 'XYZ-18.txt']
def func(elem):
return elem.split('-')[1].split('.')[0]
sortlist = sorted(mylist,key=func)
for i in sortlist:
print(i)
The output is-
XYZ-18.txt
XYZ-78.txt
XYZ-8.txt
I was expecting output as-
XYZ-8.txt
XYZ-18.txt
XYZ-78.txt
sorted(d, key=lambda x: int(x.split('-')[1].split('.')[0]))"8"to sort before"18"but those are strings and so sort alphabetically. Suppose they were letters, 1=A etc. You would expect"AH"to sort before"H". If you want them to be sorted as numbers you need to convert them to integers as in Rakesh's example. But you need to be sure that the second element of the code can always be converted to anint. If not, you have to trap for that.