I have a class with several different values. I would like to be able to sort a list of these object by the different values, but I am not sure how to do so. I would like to be able to sort them for any of the values and for both directions (least to greatest and vice versa).
For example below is a sample class, along with a list of sample objects:
class Sample(object):
def __init__(self, name, sampleValue1, sampleValue2):
self.name
self.value1 = sampleValue1
self.value2 = sampleValue2
def __repr__(self):
return self.name
# creating sample objects for clarification
objectNames = ['A','B','C','D']
values1 = [3,4,1,2]
values2 = [1,4,2,3]
sampleObjects = list()
for i in xrange(4):
obj = Sample(objectNames[i], values1[i], values2[i])
sampleObjects.append(obj)
Sorting sampleObjects from each of the objects values should yield what's below. Sorting should return a list of the objects in the order specified (objects names are used below).
value1: [C,D,A,B]
value1 reversed: [B,A,D,C]
value2: [A,C,D,B]
value2 reversed: [B,D,C,A]