[Tutor] manipulating data

Alan Gauld alan.gauld at btinternet.com
Tue Nov 13 10:03:00 CET 2007


"Bryan Fodness" <bryan.fodness at gmail.com> 

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

You need to create an empty list when you define field
and you need to append top that list. See the pseudo 
code I sent last time...

>> 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()
>>

Alan G.



More information about the Tutor mailing list