how can I sort a bunch of lists over multiple fields?

googleboy mynews44 at yahoo.com
Wed Apr 27 13:34:42 EDT 2005


I didn't think this would be as difficult as it now seems to me.

I am reading in a csv file that documents a bunch of different info on
about 200 books, such as title, author, publisher, isbn, date and
several other bits of info too.

I can do a simple sort over the first field (title as it turns out),
and that is fine as far as it gets:


import string

bookData = open(r'D:\path\to\books.csv', 'r')
sBookData = bookData.read()
lBooks = string.split(sBookData, '\n')

lBooks.sort()
sorted = string.join(lBooks, '\n')
output = open(r'D:\path\to\output.csv', 'w')
output.close()


I really want to be able to sort the list of books based on other
criterium, and even multiple criteria (such as by author, and then by
date.)

I am using python 2.4 and have found this site:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305304

and so I tried doing things like

>>>lBooks.sort(cmp=cmp5)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'cmp5' is not defined

(I was hoping that cmp5 meant it would use the 5th item in the lists to
sort across)

>>> lBooks.sort(key=lambda i:i[4])
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 1, in <lambda>
IndexError: string index out of range


(I was hoping for similar things)


would you be so kind as to point me in the right direction?

THanks!

googleboy




More information about the Python-list mailing list