Sorting a list
Duncan Booth
duncan.booth at invalid.invalid
Fri Feb 2 04:21:29 EST 2007
Steven Bethard <steven.bethard at gmail.com> wrote:
> You don't need to use sorted() -- sort() also takes the key= and
> reverse= arguments::
>
> >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'),
> ... ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'),
> ... ('1996', 'aaa')]
> >>> from operator import itemgetter
> >>> lines.sort(key=itemgetter(0), reverse=True)
> >>> lines
> [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'),
> ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]
I suspect you want another line in there to give the OP what they actually
want: sort the list alphabetically first and then reverse sort on the year.
The important thing to note is that the reverse flag on the sort method
doesn't reverse elements which compare equal. This makes it possible to
sort on multiple keys comparatively easily.
>>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'),
('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'),
('1996', 'aaa')]
>>> from operator import itemgetter
>>> lines.sort(key=itemgetter(1))
>>> lines.sort(key=itemgetter(0), reverse=True)
>>> lines
[('1997', 'aaa'), ('1997', 'bbb'), ('1996', 'aaa'), ('1996', 'ccc'),
('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]
More information about the Python-list
mailing list