1

I'm new here and hope you can help me with my problem.

I have a list in python with foldernames like:

List = ['file_io(0).txt','file_io(1).txt',....,'file_io(13004).txt']

and I would like to sort these files by ascending numbers in the brackets.

If I use sort(List), the files are sorted this way:

List = ['file_io(0).txt','file_io(1).txt','file_io(10).txt','file_io(100).txt',...]

Does anyone have an advice or a solution for me?

Thanks.

saeed foroughi
  • 1,662
  • 1
  • 13
  • 25
Len01
  • 31
  • 5
  • https://stackoverflow.com/q/4836710/8014793 – hurlenko Jan 31 '20 at 15:32
  • Does this answer your question? [Does Python have a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – Synoli Jan 31 '20 at 16:16

2 Answers2

1

You can use a regex to pull out the number from within the parentheses, convert that to int, then sort based on that numeric value.

>>> List = ['file_io(0).txt', 'file_io(1).txt', 'file_io(97).txt', 'file_io(100).txt', 'file_io(13004).txt']
>>> sorted(List, key=lambda i: int(re.match(r'file_io\((\d+)\).txt', i).group(1)))
['file_io(0).txt', 'file_io(1).txt', 'file_io(97).txt', 'file_io(100).txt', 'file_io(13004).txt']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

Assuming that you are sure of the structure of your file naming, use this sort key to sort your list.

lst.sort(key=lambda x:int(x[x.find("(")+1:x.find(")")]))
QuakeCore
  • 1,886
  • 2
  • 15
  • 33