i also have a file with various movies in the text.
my task: read the file and sort all the movies according to year, title, and genre.
here's my code so far:
from movie import *
for i in range(len(line)-1, -1, -1):
if line[i] == char:
m1 = 
file1 = open("movies.txt", "r")
for line in file1:
tab = line.find("\t")
newLine = line.find("\n")
tab2 = findLast(line,"\t")
title = line[:tab]
genre = line[tab2+1:newLine]
as you can see, i've taken the entire file and shoved it into a list.
is there a way i can sort the list according to title, year and genre? or am i doing this completely wrong?
By adding a __cmp__ method to class Movie, you can sort instance objects in list m1 with list method sort(). Following is an example of a __cmp__ overload in a Vector class that sorts on the x, y and z attributes:
def __cmp__(self, other, epsilon=0.000001):
x = abs(self.x-other.x)
if x < epsilon:
y = abs(self.y-other.y)
if y < epsilon:
return cmp(self.z, other.z)
return cmp(self.y, other.y)
return cmp(self.x, other.x)
You can also define your own comparison function and pass it to list method sort(). Example using Point objects: