Hello I'm trying to sort my microscpoy images. I'm using python 3.7 File names' are like this. t0, t1, t2
S18_b0s17t0c0x62672-1792y6689-1024.tif
S18_b0s17t1c0x62672-1792y6689-1024.tif
S18_b0s17t2c0x62672-1792y6689-1024.tif
.
.
.
S18_b0s17t145c0x62672-1792y6689-1024
I tried "sorted" the list but it was like this
can some one give me some tips to sort out by the sequence
CodePudding user response:
I think you can use lambda function do define the sorting key for sorted
function
lst = ["S18_b0s17t0c0x62672-1792y6689-1024.tif", "S18_b0s17t1c0x62672-1792y6689-1024.tif", "S18_b0s17t2c0x62672-1792y6689-1024.tif" , "S18_b0s17t145c0x62672-1792y6689-1024"]
sorted_lst = sorted(lst, key=lambda filename: filename[10:].split('c')[0])
CodePudding user response:
You could use a regular expression to extract the integers in the filename, this should solve the issue of 100 coming before 2.
files = ['S18_b0s17t100c0x62672-1792y6689-1024.tif','S18_b0s17t1c0x62672-1792y6689-1024.tif','S18_b0s17t2c0x62672-1792y6689-1024.tif']
sorted(files, key=lambda x: int(re.findall('S\d{1,2}\_b\ds\d{1,2}t(\d )',x)[0]))
Output
['S18_b0s17t1c0x62672-1792y6689-1024.tif',
'S18_b0s17t2c0x62672-1792y6689-1024.tif',
'S18_b0s17t100c0x62672-1792y6689-1024.tif']