preallocate list

Jim jbo at cannedham.ee.ed.ac.uk
Wed Apr 13 09:13:52 EDT 2005


rbt wrote:
> Jim wrote:
> 
>> If I have a file with a floating point number on each line, what is 
>> the best way of reading them into a list (or other ordered structure)?
>>
>> I was iterating with readline and appending to a list but it is taking 
>> ages.
> 
> 
> Perhaps you should use readlines (notice the s) instead of readline.

I don't know if I thought of that, but I'm tokenizing each line before 
adding to a list of lists.

             for line in f:
                 factor = []
                 tokens = line.split()
                 for i in tokens:
                     factor.append(float(i))
                 factors.append(factor)

Is this nasty?

Jim



More information about the Python-list mailing list