Question about nested loop

Hans Mulder hansmu at xs4all.nl
Mon Dec 31 07:59:34 EST 2012


On 31/12/12 11:02:56, Isaac Won wrote:
> Hi all,
> I am a very novice for Python. Currently, I am trying to read continuous
> columns repeatedly in the form of array. 
> my code is like below:
> 
> import numpy as np
> 
> b = [] 
> c = 4
> f = open("text.file", "r")
> 
> while c < 10:
>         c = c + 1
> 
>         for  columns in ( raw.strip().split() for raw in f ):
>                 b.append(columns[c])
> 
>         y = np.array(b, float)
>         print c, y
> 
> 
> I thought that  can get the arrays of the columns[5] to [10], but I only
> could get repetition of same arrays of columns[5].
> 
> The result was something like:
> 
> 5 [1 2 3 4 ......, 10 9 8]
> 6 [1 2 3 4 ......, 10 9 8]
> 7 [1 2 3 4 ......, 10 9 8]
> 8 [1 2 3 4 ......, 10 9 8]
> 9 [1 2 3 4 ......, 10 9 8]
> 10 [1 2 3 4 ......, 10 9 8]
> 
> 
> What I can't understand is that even though c increased incrementally upto 10,
> y arrays stay same.
> 
> Would someone help me to understand this problem more?

That's because the inner loop read from a file until his reaches
the end of the file.  Since you're not resetting the file pointer,
during the second and later runs of the outer loop, the inner loop
starts at the end of the file and terminates without any action.

You'd get more interesting results if you rewind the file:

import numpy as np

b = []
c = 4
f = open("text.file", "r")

while c < 10:
        c = c + 1

        f.seek(0,0)
        for  columns in ( raw.strip().split() for raw in f ):
                b.append(columns[c])

        y = np.array(b, float)
        print c, y

It's a bit inefficient to read the same file several times.
You might consider reading it just once.  For example:

import numpy as np

b = []

f = open("text.file", "r")
data = [ line.strip().split() for line in f ]
f.close()

for c in xrange(5, 11):
        for row in data:
                b.append(row[c])

        y = np.array(b, float)
        print c, y


Hope this helps,

-- HansM






More information about the Python-list mailing list