Order file based on numbers in name

I have a bunch of file with names as follows:

tif_files = av_v5_1983_001.tif, av_v5_1983_002.tif, av_v5_1983_003.tif...av_v5_1984_001.tif, av_v5_1984_002.tif...av_v5_2021_001.tif, av_v5_2021_002.tif

However, they are not guaranteed to be in any sort of order.

I want to sort them based on names such that files from the same year are sorted together. When I do this

sorted(tif_files, key=lambda x:x.split('_')[-1][:-4]) 

I get the following result:

av_v5_1983_001.tif, av_v5_1984_001.tif, av_v5_1985_001.tif...av_v5_2021_001.tif

but I want this:

av_v5_1983_001.tif, av_v5_1983_002.tif, av_v5_1983_003.tif...av_v5_1984_001.tif, av_v5_1984_002.tif...av_v5_2021_001.tif, av_v5_2021_002.tif

Answer

if you have v1 or v2 or … v5 or … you need to consider number of version also like below:

tif_files = ['av_v1_1983_001.tif', 'av_v5_1983_002.tif', 'av_v6_1983_002.tif','av_v5_1984_001.tif', 'av_v5_1984_002.tif', 'av_v4_2021_001.tif','av_v5_2021_001.tif', 'av_v5_2021_002.tif', 'av_v4_1984_002.tif']

sorted(tif_files, key=lambda x: [x.split('_')[2:], x.split('_')[1]])

Output:

['av_v1_1983_001.tif',
 'av_v5_1983_002.tif',
 'av_v6_1983_002.tif',
 'av_v5_1984_001.tif',
 'av_v4_1984_002.tif',
 'av_v5_1984_002.tif',
 'av_v4_2021_001.tif',
 'av_v5_2021_001.tif',
 'av_v5_2021_002.tif']