Problem to read from array
Peter Otten
__peter__ at web.de
Sat Nov 21 06:23:31 EST 2015
vostrushka at gmail.com wrote:
> Hi,
> I have a file with one parameter per line:
> a1
> b1
> c1
> a2
> b2
> c2
> a3
> b3
> c3
> ...
> The parameters are lines of characters (not numbers)
>
> I need to load it to 2D array for further manipulations.
> So far I managed to upload this file into 1D array:
>
> ParametersRaw = []
No need for this assignment as you throw the value away.
> with open(file1) as fh:
> ParametersRaw = fh.readlines()
> fh.close()
The with open() ... statement already ensures that the file is closed.
> NumberOfColumns = 7
> NumberOfRows = len(ParametersRaw)/NumberOfColumns
>
> Parameters = [[],[]]
> i=0
> j=0
> k=0
> while (i < NumberOfRows):
> while (j < NumberOfColumns):
> k = (i*NumberOfColumns)+j
> Parameters[i][j] = ParametersRaw[k]
The inner lists Parameters[i] are empty so every assignment
Parameters[i][k] = ...
will fail. While the minimal fix is to use append()
Parameters[i].append(ParametersRaw[k])
you will run into the same problem with the rows if there are more than the
two you prepared for in the line
> Parameters = [[],[]]
> j = j + 1
> i = i + 1
> j = 0
>
> it fails at the line "Parameters[i][j] = ParametersRaw[k]" with error:
>
> IndexError: index 0 is out of bounds for axis 0 with size 0
>
> In case of populating 1D array I would use append() method.
> But in case of 2D I am lost of how append() can be applied.
> Could some one help newbie.
As a general remark in idiomatic Python the loop
i = 0
while i < THRESHOLD:
...
i = i + 1
is written as a for loop with range():
for i in range(THRESHOLD):
...
For your specific problem list slicing is a good approach:
COLUMNS = 7
with open(file1) as f:
parameters_raw = f.readlines()
parameters = []
for row_start in range(0, len(parameters_raw), COLUMNS):
parameters.append(parameters_raw[row_start:row_start+COLUMNS])
More information about the Python-list
mailing list