[Tutor] problem loading and array from an external file
Hugo Arts
hugo.yoshi at gmail.com
Tue Aug 10 18:11:26 CEST 2010
On Tue, Aug 10, 2010 at 9:59 AM, bob gailer <bgailer at gmail.com> wrote:
> On 8/10/2010 10:42 AM, Bill Allen wrote:
>>
>> Bob,
>>
>> I was really off on that algorithm and had way over complicated it.
>> I have it working correctly now, but for the sake of those who saw my
>> earlier really botched code, here is the resultant code that works.
>> The entire inner loop and intermediate variables are removed, but
>> shown commented out. I had somehow thought I needed to read each
>> member of each subarray in individually. That was not the case and
>> that inner loop was overwriting the array.
>>
>> # reads one line at a time from file and puts data into array
>> for line in textf:
>> #tempwords = line.split(None)
>> #for n in range(0, len(room)-1):
>> # roomx[n] = tempwords[n]
>> #room[m] = roomx
>> room[m] = line.split(None)
>> m += 1
>>
>>
>
> Great. Good work. Teach a man to fish?
>
> Now for the refinements. First you can use enumerate to obtain the room
> index:
>
> for m, line in enumerate(textf):
> room[m] = line.split(None)
>
>
> Second you can start with an empty list and append:
>
> rooms = []
> for line in textf:
> rooms.append(line.split(None))
>
> Third you can use list comprehension:
>
> rooms = [line.split(None) for line in textf]
>
Nice going, this is the best way of getting your answer from the
tutors list IMO, high fives all around. I wish more threads went like
this.
You don't actually have to specify the None in line.split AFAIK, but
it might be better to be explicit. thoughts on this, anyone?
Hugo
More information about the Tutor
mailing list