3

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]

1 Answer 1

7

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.