[Tutor] problem loading and array from an external file
bgailer at gmail.com
Tue Aug 10 16:59:10 CEST 2010
On 8/10/2010 10:42 AM, Bill Allen wrote:
> 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
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:
Third you can use list comprehension:
rooms = [line.split(None) for line in textf]
Chapel Hill NC
More information about the Tutor