Sorting list (maybe stupid)

Harvey Thomas hst at empolis.co.uk
Tue Jun 11 05:59:08 EDT 2002


Järvinen Petri wrote
> 
> Hey,
> 
> I have a problem and can't solve it:
> 
> There is lines of text like:
> 
> 2. Header2
> 1. Header1
> 102. Header102
> 
> and so on...
> 
> And I need to sort them according to the number (1,2,3,4...)
> 
> Am I missing something.. I have tried to split the lines by 
> whitespace and 
> create lists. But how can i sort the list by first element...
> 
> Thanks, Petri
> -- 

Here's a quick and dirty 2.2 program illustrating one way. It uses a regular expression to extract the leading number, creates a tuple of the leading number (zero if none) and the original text. It then sorts the list of tuples in place and prints the
second element of each tuple.

import re

r = re.compile('\d+')
afile = open('myfile.txt')
tuplelist = []
for aline in afile:
    m = r.match(aline)
    if m:
        tuplelist.append((int(m.group(0)), aline))
    else:
        tuplelist.append((0, aline))
tuplelist.sort()
for x in tuplelist:
    print x[1]

HTH

Harvey

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.





More information about the Python-list mailing list