[Tutor] problem loading and array from an external file
wallenpb at gmail.com
Thu Aug 12 01:41:58 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:
>> 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]
> Bob Gailer
> Chapel Hill NC
I had not gotten back on the email until just now. I figured out the
second method today on my own. That third method is fascinating. I
have not heard of "list comprehension" before. That must be unique
Python lingo. What is the principle behind that?
Thanks for the help.
More information about the Tutor