Sorting a list

Steven Bethard steven.bethard at gmail.com
Thu Feb 1 16:12:15 EST 2007


Bruno Desthuilliers wrote:
> If you want to prevent this from happening and don't mind creating a 
> copy of the list, you can use the sorted() function with the key and 
> reverse arguments and operator.itemgetter:
> 
>  >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), 
> ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')]
>  >>> from operator import itemgetter
>  >>> sorted(lines, key=itemgetter(0), reverse=True)
> [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), 
> ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]

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')]

STeVe



More information about the Python-list mailing list