0

I have a list with 240 figures all starting with the fig and the number of the fig.

Here is an example :

fig1-24-24-32
fig3-45-32-12
fig2-24-24-31
fig5-24-24-31
fig6-24-24-31
fig4-24-24-31

I would like to order that list by fig name:

fig1-24-24-32
fig2-24-24-31
fig3-45-32-12
fig4-24-24-31
fig5-24-24-31
fig6-24-24-31

I have tried :

print(glob.glob('fig*[1-241]*'))

However this does not work This is what I getoutput

UPDATE Found the answer to my question here: https://stackoverflow.com/a/2669120/6235069 Answer is given by @Mark Byers

2 Answers2

2

I am assuming here that all the files start with the same 3-character long prefix ( does not have to be 'fig'; will not be taken into account) which in turn is followed by digits (one or many) until a dash ('-') is met.

If that is indeed the case, you can use the following:

sorted(my_files, key=lambda x: int(x.split('-')[0][3:]))

Note that my_files is a list containing all the filenames (basenames).

Output:

['fig1-24-24-32', 
 'fig2-24-24-31', 
 'fig3-45-32-12', 
 'fig4-24-24-31', 
 'fig5-24-24-31', 
 'fig6-24-24-31']
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • Thank you the logical explantation seems right however I have this error when running the script over my 240 figures: ValueError: invalid literal for int() with base 10: 'ig144' – Pierre Jardinet Jan 26 '18 at 14:55
0

Below code will do you job:

mylist=['fig1-24-24-32',
'fig3-45-32-12',
'fig2-24-24-31',
'fig5-24-24-31',
'fig6-24-24-31',
'fig4-24-24-31']

updated_list=sorted(mylist)

Sorted will do your job until and unless you want to sort on the first 3 characters.

updated_list

['fig1-24-24-32',
 'fig2-24-24-31',
 'fig3-45-32-12',
 'fig4-24-24-31',
 'fig5-24-24-31',
 'fig6-24-24-31']
user15051990
  • 1,835
  • 2
  • 28
  • 42