简体   繁体   中英

Sort filenames in directory in ascending order with two levels

I have a directory with .jpg files (frames from different video files). Filenames look like 'frame_{}_{}'.format(number_of_video, frame_number). For example: 'frame_1_1234.jpg'

How I can sort files in ascending order with two-level sorting? Firstly by number_of_video and secondly by frame_number.

Now I have this:

['frame_0_0.jpg','frame_0_1.jpg','frame_0_10.jpg','frame_0_100.jpg','frame_0_1000.jpg','frame_0_1001.jpg','frame_0_1002.jpg','frame_0_1003.jpg','frame_0_1004.jpg','frame_0_1005.jpg','frame_0_1006.jpg','frame_0_1007.jpg',...]

I want to have this:

['frame_0_0.jpg', 'frame_0_1.jpg', 'frame_0_2.jpg',..., 'frame_1_0.jpg', 'frame_1_1.jpg', 'frame_1_2.jpg',...]

Clearly .sorted() blindly the most significant number first.

You could use the key parameter of sorted :

import re


def key(value):
    """Extract numbers from string and return a tuple of the numeric values"""
    return tuple(map(int, re.findall('\d+', value)))


values = ['frame_0_0.jpg', 'frame_0_1.jpg', 'frame_0_10.jpg', 'frame_0_100.jpg',
          'frame_0_1000.jpg', 'frame_0_1001.jpg', 'frame_0_1002.jpg', 'frame_0_1003.jpg',
          'frame_0_1004.jpg', 'frame_0_1005.jpg', 'frame_0_1006.jpg', 'frame_0_1007.jpg']

result = sorted(values, key=key)
print(result)

Output

['frame_0_0.jpg', 'frame_0_1.jpg', 'frame_0_10.jpg', 'frame_0_100.jpg', 'frame_0_1000.jpg', 'frame_0_1001.jpg', 'frame_0_1002.jpg', 'frame_0_1003.jpg', 'frame_0_1004.jpg', 'frame_0_1005.jpg', 'frame_0_1006.jpg', 'frame_0_1007.jpg']

Notice that the key uses a regular expression for finding the numbers inside the string, you can find more about them, here .

You might want to create a list of tuples (number_of_video, frame_number) , sort the list, and after that create the filenames.

tuples = [(0,0), (0,1), (0,10), (0,100), (0,1000), ...]
filenames = [f"frame_{t[0]}_{t[1]}.jpg" for t in sorted(tuples)]

you could try this too.

set1 = ['frame_0_0.jpg','frame_0_1.jpg','frame_2_10.jpg','frame_1_100.jpg','frame_0_1000.jpg','frame_0_1001.jpg','frame_0_1002.jpg','frame_0_1003.jpg']

set1.sort() #will sort the elements present inside the list

If you print the set1 again, you will get it as: ['frame_0_0.jpg', 'frame_0_1.jpg', 'frame_0_1000.jpg', 'frame_0_1001.jpg', 'frame_0_1002.jpg', 'frame_0_1003.jpg', 'frame_1_100.jpg', 'frame_2_10.jpg']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM