avoding the accumulation of array when using loop.

Isaac Won winefrog at gmail.com
Wed Jan 2 17:21:11 EST 2013


Hi all,

Thanks to Hans, I have had a good progress on my problem. 

Followings are Hans's Idea:

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

It is a great idea, but I found some problems. I want each individual array of y. However, these two codes prodce accumulated array such as [1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9] and so on. I have tried to initialize for loop for each time to produce array. This effort has not been very successful.
Do you guys have any idea? I will really appreciate ant help and idea.

Thanks,

Isaac



More information about the Python-list mailing list