Sorting list (maybe stupid)

Russell Blau russblau at hotmail.com
Tue Jun 11 12:05:43 EDT 2002


"Max M" <maxm at mxm.dk> wrote in message news:3D05F3FD.7020202 at mxm.dk...
> afile = open('myfile.txt')
> tuplelist = []
> for aline in afile:
>      nummericValue = int(aline[:aline.find('.')])
>      tuplelist.append((nummericValue, aline))
> tuplelist.sort()
> sortedLines = [tup[1] for tup in tuplelist]
> for line in sortedLines:
>      print line

If the programmer is *certain* that each line will be in the format
given by the OP, which is a line number followed by a period and a
space, followed by arbitrary text, then the solution can be even
simpler:

linelist = []
for aline in afile:
    linelist.append(aline.split(".", 1))
# each entry in linelist is a list of two elements: [line_number,
line_body]
linelist.sort()
resultlist = []
for item in linelist:
    resultlist.append(".".join(item))
# used resultlist in case the OP wants to do something with these lines
besides just print them
# alternately, you could join the strings in-place in linelist
for line in resultlist:
    print line

--
I don't actually have a hotmail account; but I do have one on excite.com
if you really want to get in touch with me.






More information about the Python-list mailing list