Sorting a list

John Salerno johnjsal at NOSPAMgmail.com
Thu Feb 1 14:55:47 EST 2007


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. :)

Here's what I did:

import re

file = open('newrefs.txt')
text = file.readlines()
file.close()

newfile = open('sortedrefs.txt', 'w')
refs = []

pattern = re.compile('\(\d{4}\)')

for line in text:
     year = pattern.search(line).group()
     refs.append((year, line))

refs.sort()

for ref in refs:
     newfile.write(ref[1])

newfile.close()



More information about the Python-list mailing list