I have a list of objects of the same type
lis = [<obj>, <obj>, <obj>]
that I wish to sort naturally by the object attribute name. I have tried
sortedlist = sorted(lis, key=lambda x: x.name)
However this sorts the list as
A1
A10
A2
Not in the format that I wanted
A1
A2
A10
I have tried modifying the code from sorting alphanumeric strings, but I can't get it working for a list of objects.
This way uses groupby, and works for an arbitrary number of swaps between alpha and digits
from itertools import groupby
def keyfunc(s):
return [int(''.join(g)) if k else ''.join(g) for k, g in groupby(s, str.isdigit)]
sorted(my_list, key=keyfunc)
Demo:
>>> my_list =['A1', 'A10', 'A2', 'B0', 'AA11', 'AB10']
>>> sorted(my_list, key=keyfunc)
['A1', 'A2', 'A10', 'AA11', 'AB10', 'B0']
>>> mylist =['foo1', 'foo10', 'foo2', 'foo2bar1', 'foo2bar10', 'foo2bar3']
>>> sorted(mylist, key=keyfunc)
['foo1', 'foo2', 'foo2bar1', 'foo2bar3', 'foo2bar10', 'foo10']
sorted(obj, key=lambda x: (x.name[0], int(x.name[1:])))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With