Python natural sort by object attribute
I wanted to sort a list of custom classes in Python. I wanted to sort the list by the .albumid attribute of the objects. A natural sort is where the order is 1-9, 10-19, 20-29, etc., instead of 1, 10-19, 2, 20-29, 3, 30-39, etc. It is very useful for when you want to sort a string that nominally has numbers at the beginning.
def natural_sort(l, attrib):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key.__dict__[attrib])]
return sorted(l, key=alphanum_key)
results = natural_sort(albums, 'albumid')
I posted this insight on Stackoverflow.
Comments