简体   繁体   中英

sorted() function not working on numeric list

I am trying to get the order of all files in the directory so I tried using sorted() function to sort the numeric value of each file which are respectively named folder/frame0.jpg . The problem is I am getting an output that looks like this

yourlieinapril1/frame1094.jpg
yourlieinapril1/frame1095.jpg
yourlieinapril1/frame1096.jpg
yourlieinapril1/frame1097.jpg
yourlieinapril1/frame1098.jpg
yourlieinapril1/frame1099.jpg
yourlieinapril1/frame1100.jpg
yourlieinapril1/frame110.jpg
yourlieinapril1/frame1101.jpg

when ever it iterates through a base ten number the list goes back to a lesser number which I tried fixing with the following code but it still doesn't work well

def animate(folder):
    l = list()
    a = list()
    for filename in os.listdir(folder):
        path = (os.path.join(folder, filename))
        if path.endswith('jpg'):
            num = ''
            for i in range(len(path)):
                try:
                    p = int(path[i])
                    num += str(path[i])
                except:
                    pass
            try:
                check = a[len(a) - 1]
                if len(check) > len(num):
                    if num != '0':
                        num += ('0')
                        path = folder + '/frame' + num + '.jpg'
            except:
                pass
            a.append(num)
            l.append(path)
    f = sorted(l)
    f = list(dict.fromkeys(f))

does anyone have an idea of how I should do this?

Specify a key parameter to sorted to tell it how to sort the strings that's different from standard alphabetical comparison.

>>> files = [
...     "yourlieinapril1/frame1094.jpg",
...     "yourlieinapril1/frame1095.jpg",
...     "yourlieinapril1/frame1096.jpg",
...     "yourlieinapril1/frame1097.jpg",
...     "yourlieinapril1/frame1098.jpg",
...     "yourlieinapril1/frame1099.jpg",
...     "yourlieinapril1/frame1100.jpg",
...     "yourlieinapril1/frame110.jpg",
...     "yourlieinapril1/frame1101.jpg",
... ]
>>> sorted(files, key=lambda s: int(s[21:-4]))
['yourlieinapril1/frame110.jpg', 'yourlieinapril1/frame1094.jpg', 'yourlieinapril1/frame1095.jpg', 'yourlieinapril1/frame1096.jpg', 'yourlieinapril1/frame1097.jpg', 'yourlieinapril1/frame1098.jpg', 'yourlieinapril1/frame1099.jpg', 'yourlieinapril1/frame1100.jpg', 'yourlieinapril1/frame1101.jpg']

If your real data set is more complicated (ie the leading non-numeric part is variable and you want to sort on that plus the numeric value), your key function might instead do something like returning a tuple of the leading str and the trailing int .

You need to index the filenames by the number in the filename (by first extracting the number in the first place), and then zero-pad the number, and sort the index. Like this:

import os

def index_frames(folder):
    indexed_files = {}
    for filename in os.listdir(folder):
        path = (os.path.join(folder, filename))
        if path.endswith('jpg'):
            # extract the number from the filename and pad with zeros so that they will sort correctly
            num = ''.join([s for s in filename if s.isdigit()]).zfill(15)
            
            # insert into a dict with key as padded number
            indexed_files[num] = path

    return indexed_files

index_frames = index_frames('yourlieinapril1')
for key in sorted(index_frames.keys()):
    # these will print in order because they have been sorted by the index
    print(index_frames[key])

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