Sorting a list

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Feb 1 16:28:58 EST 2007


John Salerno a écrit :
> John Salerno wrote:
> 
>> Bruno Desthuilliers wrote:
>>
>>> John Salerno a écrit :
>>>
>>>> Hi everyone. If I have a list of tuples, and each tuple is in the form:
>>>>
>>>> (year, text) as in ('1995', 'This is a citation.')
>>>>
>>>> How can I sort the list so that they are in chronological order 
>>>> based on the year?
>>>
>>>
>>> Calling sort() on the list should just work.
>>
>>
>> Amazing, it was that easy. :)
> 
> 
> One more thing. What if I want them in reverse chronological order? I 
> tried reverse() but that seemed to put them in reverse alphabetical 
> order based on the second element of the tuple (not the year).

Really ?

 >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), 
('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')]
 >>> lines.sort()
 >>> lines
[('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc'), ('1996', 'aaa'), 
('1996', 'ccc'), ('1997', 'aaa'), ('1997', 'bbb')]
 >>> lines.reverse()
 >>> lines
[('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), 
('1995', 'ccc'), ('1995', 'bbb'), ('1995', 'aaa')]
 >>>

As you see, the list is being sorted on *both* items - year first, then 
sentence. And then of course reversed, since we asked for it !-)

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

HTH.



More information about the Python-list mailing list