Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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]
like image 475
David C Avatar asked Aug 07 '26 22:08

David C


1 Answers

Python built-in sorted function has signature:

sorted(iterable[, cmp[, key[, reverse]]])

and

key specifies a function of one argument that is used to extract a comparison key from each list element

For your case:

>>> sorted(sampleObjects, key=lambda obj: obj.value1)
[C, D, A, B]
>>> sorted(sampleObjects, key=lambda obj: obj.value2)
[A, C, D, B]
like image 80
behzad.nouri Avatar answered Aug 10 '26 12:08

behzad.nouri



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!