0

I would like to sort a list of subfolder names by Python but it does not work in the desired manner.

files = ['file_37.png', 'file_8.png', 'file_13.png', 'file_114.png', 'file_115.png']
sorted(files)

Output:

['file_114.png', 'file_115.png', 'file_13.png', 'file_37.png', 'file_8.png']

Apparently, Python is sorting the names in a dictionary form without considering the integer value of the digit after '_'. However, what I want to get is:

['file_8.png', 'file_13.png', 'file_37.png','file_114.png', 'file_115.png']

Can anyone tell me how to get this desired output in Python?

Grass
  • 15
  • 1
  • 5

1 Answers1

0

You can use key which is useful for sorting in your own way

key will take the function as parameter. What I have done is that I have split the string with _ and took its second part (index 1). For example if file_37.png is split using _ then it will give list of ['file', '37.png']. So using 1 as index will return 37.png. It is then again split using . and I have used the 0 index which returns the file number.

def split_x(x):
  a = x.split('_')[1]
  a = a.split('.')[0]
  return int(a)

files = ['file_37.png', 'file_8.png', 'file_13.png', 'file_114.png', 'file_115.png']
sorted(files, key=split_x)
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25