by Matias Herranz
Custom sorting function as parameter to sorted() in Python
I am currently working with Python and I came across a list of image names which I’d like to sort. So, I call the sorted function with this list:
Unfortunately, it doesn’t work as well as I would have liked. So I asked myself: What can be done to sort the list as I want it to be sorted?
Python’s standard library sorted function, as you can see here, has an optional cmp parameter, through which one can pass a custom comparison function.
Going back to my example, I needed the images to be compared by the number in their name. For that reason I made this little function to achieve this goal:
And now let’s put all together:
Matias Herranz is as a Python Developer for Santex. He is a Computer Science and Open Source software enthusiast. His professional experience has focused on Python/Django web app development and some incursions in mobile apps for iPhone/Android. He is a team player who enjoys and finds it rewarding to share the things he learns, either through conferences and lectures, or through day-to-day communication with his coworkers.