So, I am working with Python and I come across a list of image names, and I'd like to have them sorted. So, I call the sorted function with this list:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In [1]: images_list | |
['Page1.png', | |
'Page10.png', | |
'Page11.png', | |
'Page12.png', | |
'Page13.png', | |
'Page14.png', | |
'Page2.png', | |
'Page3.png', | |
'Page4.png', | |
'Page5.png', | |
'Page6.png', | |
'Page7.png', | |
'Page8.png', | |
'Page9.png'] | |
In [2]: sorted(images_list) | |
Out[2]: | |
['Page1.png', | |
'Page10.png', | |
'Page11.png', | |
'Page12.png', | |
'Page13.png', | |
'Page14.png', | |
'Page2.png', | |
'Page3.png', | |
'Page4.png', | |
'Page5.png', | |
'Page6.png', | |
'Page7.png', | |
'Page8.png', | |
'Page9.png'] |
HA! It doesn't work as I would have liked it to. So, what can we do to achieve the sorting of the list as we want it?
Python's standard library sorted function, as you can see here, has an optional cmp parameter, through which you can pass a custom comparison function.
Going back to my example, I needed the images to be compared by the number in their name. I made this little function to achieve this goal:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def custom_cmp(item1, item2): | |
""" Helper function to use as 'cmp' parameter when sorting the list of | |
.png pages in the unzipped pages images list. | |
""" | |
n1 = item1.split('.')[0][4:] | |
n2 = item2.split('.')[0][4:] | |
return int(n1) - int(n2) |
And now let's put altogether:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In [5]: sorted(images_list, cmp=custom_cmp) | |
Out[5]: | |
['Page1.png', | |
'Page2.png', | |
'Page3.png', | |
'Page4.png', | |
'Page5.png', | |
'Page6.png', | |
'Page7.png', | |
'Page8.png', | |
'Page9.png', | |
'Page10.png', | |
'Page11.png', | |
'Page12.png', | |
'Page13.png', | |
'Page14.png'] |
TA DA!