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

James Stroud jstroud at mbi.ucla.edu
Wed Apr 27 14:07:29 EDT 2005


Oops, last one had a typo:


a = ['bob', 'greg', 'cindy', 'alice']
b = ['fred','barney','betty','wilma','pebbles','bambam']
c = ['jed', 'granny', 'jethro', 'ellie-mae']
d = ['bob','carol','ted','alice']

e = [a,b,c,d]

for ary in e:
  print ary

e.sort(lambda x,y:cmp(x[1],y[1]))

for ary in e:
  print ary

e.sort(lambda x,y:cmp(x[0],y[0]))

for ary in e:
  print ary

James

On Wednesday 27 April 2005 10:34 am, so sayeth googleboy:
> 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

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list