Python arrays and sting formatting options

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Sep 30 20:32:28 EDT 2008


En Mon, 29 Sep 2008 19:04:18 -0300, Ivan Reborin  
<ireborin at delete.this.gmail.com> escribió:

> 1. Multi dimensional arrays - how do you load them in python
> For example, if I had:
> -------
> 1 2 3
> 4 5 6
> 7 8 9
>
> 10 11 12
> 13 14 15
> 16 17 18
> -------
> with "i" being the row number, "j" the column number, and "k" the ..
> uhmm, well, the "group" number, how would you load this ?

I agree that using NumPy is the way to go if you're going to do lots of  
array calculations. But a plain Python code would look like this (more  
comprehensible than other posted versions, I hope):

--- begin code ---
def read_group(fin, rows_per_group):
     rows = []
     for i in range(rows_per_group):
         line = fin.readline()
         row = [float(x) for x in line.split()]
         rows.append(row)
     fin.readline() # skip blank line
     return rows

# simulate a file using a string instead
# actual code would use: fin = open(filename)

 from StringIO import StringIO
fin = StringIO("""1 2 3
4 5 6
7 8 9

10 11 12
13 14 15
16 17 18
""")

# read 2 groups of 3 lines each
matrix = [read_group(fin, 3) for k in range(2)]
print matrix
--- end code ---

A more compact version of read_group (collapsing all rows.append onto the  
outer list comprehension):

--- begin code ---
def read_group(fin, rows_per_group):
     rows = [[float(x) for x in fin.readline().split()]
                  for i in range(rows_per_group)]
     fin.readline() # skip blank line
     return rows
--- end code ---

-- 
Gabriel Genellina




More information about the Python-list mailing list