How to sort a list of objects based on different object values in python?
I have a class with several different values. I would like to be able to sort the list of these objects by different values, but I am not sure how. I would like to be able to sort them for any values and for both directions (smallest to largest and vice versa).
Below is an example of a class, as well as a list of example 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 object values should yield what is below. Sorting should return a list of objects in the specified order (object 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]
+3
source to share
1 answer
The sorted
Python built-in function is signed:
sorted(iterable[, cmp[, key[, reverse]]])
and
Keyspecifies a single argument function that is used to extract the comparison key from each item in the list
In your case:
>>> sorted(sampleObjects, key=lambda obj: obj.value1)
[C, D, A, B]
>>> sorted(sampleObjects, key=lambda obj: obj.value2)
[A, C, D, B]
+7
source to share