I have problem with sort()

hi I’m having difficulties with making datasets.
I have 2 folders. One with image files and the other one with the mask files.
I tried to make the data in order using sort()
the image data were lined like 1, 10, 11, 12, 13
but mask data were like 10, 11, 12, 13, …, 19, 1

how can I solve this problem??

I don’t see what is the problem, can you explain some more?

Mask files and image files has the exact same name but the mask files have ‘_mask’ on the back.
So If I use sort() for both image files and mask files, the order should be the same
But it didn’t just I mentioned above

Based on your file names, the order is also wrong, as you didn’t prepend zeros to the actual number.
E.g. after 1 comes the file with 10 in your images.
You could use sorted with a lambda function as the key argument, get the desired file index and ignore the rest of the string.

2 Likes

thank you I solved this problem using sorted with lambda function.
but I don’t understand this part.
what’s the meaning of

?

If you prepend leading zeros to the numbers, Python should be able to sort them properly.
E.g.:

my_list = sorted([str(i) for i in range(20)])
print(my_list) # wrong order

my_list = sorted(["{:04d}".format(i) for i in range(20)])
print(my_list) # right order
1 Like