Chris Headleand
Chris Headleand

Reputation: 6193

Sort a list of python objects based on a local vairable

I need to sort a list of python objects by a local variable.

For example I have a list of objects of class item;

class item():
    nummber1 = random.randInt(0, 100)
    nummber2 = random.randInt(0, 100)

listOfObjects = []
for i in range(0, 20)
    listOfObjects.append(item())

However, now I have that list I need to sort it based on the number1 local variable...

I have tried:

listOfObjects = listOfObjects.sort()

However, this doesnt seam to sort by either number1 or number2 local variable... I'm actually not sure what the list is being sorted by...

Can anyone point me in the right direction?

Upvotes: 0

Views: 211

Answers (3)

R Sahu
R Sahu

Reputation: 206667

There are few small problems in your code. But the answer to your question is that you can use sorted to which you can provide the key to be used to compare the items in the list.

import random

class item():
    def __init__(self):
        self.number1 = random.randint(0, 100)
        self.number2 = random.randint(0, 100)

    def __repr__(self):
        return "[" + str(self.number1) + ", " + str(self.number2) + "]"

def __str__(self):
        return self.__repr__()

listOfObjects = []
for i in range(0, 20):
    listOfObjects.append(item())

def getKey(item):
    return item.number1

print(sorted(listOfObjects, key=getKey))

Sample output:

[[3, 18], [12, 11], [12, 17], [25, 41], [32, 48], [37, 1], [44, 85], [49, 39], [53, 11], [63, 57], [67, 0], [69, 34], [70, 23], [78, 25], [78, 17], [80, 87], [85, 70], [87, 29], [95, 28], [96, 44]]

Upvotes: 0

jh314
jh314

Reputation: 27802

You can do:

listOfObjects.sort(key=lambda x: x.number1)

The .sort will return None and will sort in place

Upvotes: 1

Ben Wilber
Ben Wilber

Reputation: 893

You can use a key function like so:

listOfObjects = sorted(listOfObjects, key=lambda item: item.number1)

Upvotes: 2

Related Questions