Using class-attribute as key to sort?

C

cnb

In median grade, can I sort on Review-grade somehow?
something like:
sr = self.reviews.sort(key=self.reviews.instance.grade)

class Review(object):
def __init__(self, movieId, grade, date):
self.movieId = movieId
self.grade = grade
self.date = date

class Customer(object):
def __init__(self, idnumber, review):
self.idnumber = idnumber
self.reviews = [review]

def addReview(self, review):
self.reviews.append(review)

def averageGrade(self):
tot = 0
for review in self.reviews:
tot += review.grade
return tot / len(self.reviews)

#general sort that takes list+spec of objectkey to sort on?
def sortReviews(self):
def qsort(lista):
if len(lista) != 0:
return qsort([x for x in lista[1:] if x.grade <
lista[0].grade]) + [lista[0]] + \
qsort([x for x in lista[1:] if x.grade >=
lista[0].grade])
else:
return []
return qsort(self.reviews)

def medianGrade(self):
length = len(self.reviews)
sr = self.sortReviews()
#sr = self.reviews.sort(key=self.reviews.instance.grade)
if length % 2 == 0:
return (sr[int(length/2)].grade + sr[int(length/
2-1)].grade) / 2
else:
if length == 1:
return sr[0].grade
else:
return sr[int(round(length/2)-1)].grade
 
C

Chris Rebert

Just use the "key" argument to list.sort; e.g.

class Foo(object):
def __init__(self, x):
self.x = x
def __repr__(self):
return "Foo:"+str(self.x)

foos = [Foo(75), Foo(10), Foo(-1)]
foos.sort(key = lambda foo: foo.x)
print foos #=> [Foo:-1, Foo:10, Foo:75]

- Chris
========
Follow the path of the Iguana...
http://rebertia.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top