Using class-attribute as key to sort?

cnb circularfunc at yahoo.se
Fri Aug 29 20:22:22 CEST 2008


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



More information about the Python-list mailing list