How can I sort a list of python objects by attribute based on a defined mapping
E.g.
import random
class Obj(object):
attr = None
def __init__(self, attr):
self.attr = attr
def __repr__(self):
return self.attr
attrs = ['GROUPA', 'GROUPB', 'GROUPC']
objects = []
for x in range(0, 10):
objects.append(Obj(random.choice(attrs)))
objects = sorted(objects, key=lambda o: o.attr)
print '['
for o in objects:
print o
print ']'
Gives me
[
GROUPA
GROUPA
GROUPA
GROUPA
GROUPB
GROUPB
GROUPB
GROUPB
GROUPC
GROUPC
]
Which is nice, but I would like to define a mapping and take it into account while sorting, for example:
mapping = ['GROUPB', 'GROUPA', 'GROUPC']
result:
[
GROUPB
GROUPB
GROUPB
GROUPB
GROUPA
GROUPA
GROUPA
GROUPA
GROUPC
GROUPC
]
and then get the result like this