Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save amboxer21/23ceee86a3910134fdbd1247ecc0a933 to your computer and use it in GitHub Desktop.
Save amboxer21/23ceee86a3910134fdbd1247ecc0a933 to your computer and use it in GitHub Desktop.
sorting(true numerical sorting) names with numbers using nested list comprehension
# sorting a list of strings whos values are ints.
>>> numbers = ['100','11','21','200']
>>> sorted(numbers)
['100', '11', '200', '21']
>>>
# Sorting that same list using list comprehension to convert the values into ints before sorting
>>> numbers = ['100','11','21','200']
>>> sorted([int(n) for n in numbers])
[11, 21, 100, 200]
>>>
# Sorting regular integers
>>> numbers = [100,11,21,200]
>>> sorted(numbers)
[11, 21, 100, 200]
>>>
# Using nested list comprehension to sort names with numbers - true sorting by numbers!
>>> import re
>>> images = ['img100.png','img11.png','img21.png','img200.png']
>>> [ 'img'+str(n)+'.png' for n in sorted([ int(r.group(2)) for r in [re.search('(^img)(\d+)(.png)',image, re.I) for image in images] ]) ]
['img11.png', 'img21.png', 'img100.png', 'img200.png']
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment