how can I sort a bunch of lists over multiple fields?
Steven Bethard
steven.bethard at gmail.com
Wed Apr 27 14:43:18 EDT 2005
James Stroud wrote:
> 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
I would probably use the key= argument instead of the cmp= argument.
Not only is it easier, but it'll probably be faster too:
py> lst = [['bob', 'greg', 'cindy', 'alice'],
... ['fred', 'barney', 'betty', 'wilma', 'pebbles', 'bambam'],
... ['jed', 'granny', 'jethro', 'ellie-mae'],
... ['bob', 'carol', 'ted', 'alice']]
py> import operator
py> lst.sort(key=operator.itemgetter(3))
py> lst
[['bob', 'greg', 'cindy', 'alice'], ['bob', 'carol', 'ted', 'alice'],
['jed', 'granny', 'jethro', 'ellie-mae'], ['fred', 'barney', 'betty',
'wilma', 'pebbles', 'bambam']]
py> lst.sort(key=operator.itemgetter(0))
py> lst
[['bob', 'greg', 'cindy', 'alice'], ['bob', 'carol', 'ted', 'alice'],
['fred', 'barney', 'betty', 'wilma', 'pebbles', 'bambam'], ['jed',
'granny', 'jethro', 'ellie-mae']]
py> lst.sort(key=operator.itemgetter(slice(2)))
py> lst
[['bob', 'carol', 'ted', 'alice'], ['bob', 'greg', 'cindy', 'alice'],
['fred', 'barney', 'betty', 'wilma', 'pebbles', 'bambam'], ['jed',
'granny', 'jethro', 'ellie-mae']]
Note that you can pass slice objects to operator.itemgetter, so the last
example is like "key=lambda x: x[:2]".
STeVe
More information about the Python-list
mailing list