Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of objects by attribute alphanumerically

Tags:

python

sorting

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.

like image 346
Scavenger Avatar asked Mar 11 '26 16:03

Scavenger


2 Answers

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']
like image 98
John La Rooy Avatar answered Mar 14 '26 04:03

John La Rooy


sorted(obj, key=lambda x: (x.name[0], int(x.name[1:])))
like image 43
jamylak Avatar answered Mar 14 '26 04:03

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!