Sorting list (maybe stupid)

Russell Blau russblau at hotmail.com
Tue Jun 11 20:51:20 CEST 2002


"Russell Blau" <russblau at hotmail.com> wrote in message
news:ae574q$42cjd$1 at ID-76829.news.dfncis.de...
> "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
>
D'oh!  I forgot to convert the line numbers to ints before sorting.  How
about this?

linelist = []
for aline in afile:
    linenum, linebody = aline.split(".", 1)
    linelist.append((int(linenum), linebody))
linelist.sort()
resultlist = []
for linenum, linebody in linelist:
    resultlist.append(str(linenum)+"."+linebody)
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