Home > Mobile >  Reordering strings in a list based on number they contain
Reordering strings in a list based on number they contain

Time:04-27

Say I have a list of directory filepaths as strings, like so:

currently:


['/home/me/summary_generating/test_2', '/home/me/summary_generating/test_1', /home/me/summary_generating/test_3, /home/me/summary_generating/test_5]


Ideally, what I would like to do is extract any number that appears in the basename (in this case, test_*), and re-order this list so that it is in ascending order, like so:

desired:


['/home/me/summary_generating/test_1', '/home/me/summary_generating/test_2', /home/me/summary_generating/test_3, /home/me/summary_generating/test_5]


my current thinking is to try and extract the basename, use regex to identify the number in the basename, somehow index each item in the list by it's corresponding number (e.g. index 0 would be /home/me/summary_generating/test_1) and then reorder using the index. However , this seems potentially convoluted, and I was wondering if there may be a better way?

As always, any help is appreciated!

CodePudding user response:

assuming all the test_ files are in the same directory:

lst = ['/home/me/summary_generating/test_2',
       '/home/me/summary_generating/test_1',
       '/home/me/summary_generating/test_3',
       '/home/me/summary_generating/test_5']


lst.sort(key=lambda x: int(x.rsplit("_", maxsplit=1)[1]))

the sorted list is then:

['/home/me/summary_generating/test_1',
 '/home/me/summary_generating/test_2',
 '/home/me/summary_generating/test_3',
 '/home/me/summary_generating/test_5']

it sorts according to the right-most number after a "_". converting to int achieves that "test_10" will be after "test_9" (which is not what you get if you just sort by strings).

CodePudding user response:

If the directory of the files is consistent then you can just sort as is.

If you only want to sort by filename and disregard the location then you can split on '/' in your key and extract just the filename.

sorted(file_paths, key=lambda x: x.split("/")[-1])
  • Related