-3

There's a lot of alphanumeric sorting out there but I don't really understand how they work, and end up with errors on my end haahha

but here's the part of the code that makes use of the sorting I need anyways (I'm just experimenting with my project now, and this part I stumped hahah)

import os
path = 'C:\\path'

pokeimage = os.listdir(path)

which outputs

['1.jpg', '10.jpg', '100.jpg', '101.jpg', '102.jpg', '103.jpg', '104.jpg', '105.jpg', '106.jpg', '107.jpg', '108.jpg', '109.jpg', '11.jpg', '110.jpg', '111.jpg', '112.jpg', '113.jpg', '114.jpg', '115-mega.jpg', '115.jpg', '116.jpg', '117.jpg', '118.jpg', '119.jpg', '12.jpg', '120.jpg', '121.jpg', '122.jpg', '123.jpg', '124.jpg', '125.jpg', '126.jpg', '127-mega.jpg', '127.jpg', '128.jpg', ...]

so yeah they're filenames of images, I just want the list to be sorted normally like

['1.jpg', '2.jpg', '3.jpg', '4.jpg', ...]

but with the normal sort and keys and stuff, it just sorts it like the first one.

GuanSe
  • 39
  • 5
  • Those are all strings. So lexically, '10' and '100' both come before '2'. You need to treat them as numbers in order to sort them numerically. Do your research. And re-title your question. – TomServo Oct 11 '20 at 12:01

1 Answers1

1

you can define your own sorting key function to extract the file number and sort numeric by those

import re

file_names = [
    '1.jpg', '10.jpg', '100.jpg', '101.jpg', '102.jpg', '103.jpg', '104.jpg', '105.jpg', '106.jpg', '107.jpg',
    '108.jpg', '109.jpg', '11.jpg', '110.jpg', '111.jpg', '112.jpg', '113.jpg', '114.jpg', '115-mega.jpg', '115.jpg',
    '116.jpg', '117.jpg', '118.jpg', '119.jpg', '12.jpg', '120.jpg', '121.jpg', '122.jpg', '123.jpg', '124.jpg',
    '125.jpg', '126.jpg', '127-mega.jpg', '127.jpg', '128.jpg']


def sort_key(file_name):
    # match one one or more digits at the beginning of the file name
    file_number_str = re.match('[0-9]+', file_name)
    if file_number_str is not None:
        # if file number pattern is found convert the number string into an integer
        return int(file_number_str.group())
    else:
        # if file name does not start with a number return -1
        return -1


# sort file names with custom key function
file_names.sort(key=sort_key)

print(file_names)
# ['1.jpg', '10.jpg', '11.jpg', '12.jpg', '100.jpg', '101.jpg', '102.jpg', ...
Raphael
  • 1,731
  • 2
  • 7
  • 23