[Tutor] manipulating data
Bryan Fodness
bryan.fodness at gmail.com
Tue Nov 13 01:10:17 CET 2007
I have tried,
f = open('TEST1.MLC')
fields = {}
for line in f:
the_line = line.split()
if the_line:
if the_line[0] == 'Field':
field = int(the_line[-1])
elif the_line[0] == 'Leaf':
fields[field] = the_line[-1]
which, sort of works, but it overwrites each value.
On Nov 12, 2007 6:55 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> The lesson here is not to try to do two things at once...
>
> > file.next()
> > TypeError: descriptor 'next' of 'file' object needs an argument
>
> OK, My algorithm was meant to be pseudo code so file was
> not intended to be taken literally, its just a marker for an open
> file object.
>
> > And, it is true that I am trying to build a list and not overwrite
> > the value.
>
> OK, That adds a bit more tweaking...
>
> >> Personally I'd use a flag to detect when field had
> >> been found and set - ie set field to None and then
> >> test for that changing, then test for Leaf as you do.
>
> That was before I went back to testing my own project....
>
> >> So I think your algorithm should be
> >>
> >> for line in file
> >> if 'Field' in line:
> >> field = int(line.split()[-1])
>
> and this was after - with no flag anywhere in sight! Oops.
>
> I intended the if test to include a check for field == None...
>
> if field == None and 'Field' in line:....
>
> >> elif 'Leaf' in line:
> >> fields[field] = line.split()[-1]
> >> else: file.next()
> >>
> >> But I think there's another problem in that you are
> >> then overwriting the value of Leaf when I think you
> >> are trying to build a list?
>
> So we need to create an empty list entry where we
> define field and then append here, so my pseudo
> code now becomes:
>
> f = open('foo.dat')
> for line in f:
> if field == None and 'Field' in line:
> field = int(line.split()[-1])
> fields[field] = []
> elif 'Leaf' in line:
> fields[field].append(line.split()[-1])
> else: f.next()
>
> still untested I'm afraid, so it still may not work.
>
> HTH,
>
> Alan G.
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list