Re: Python arrays and sting formatting options



On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Reborin wrote:

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 ?

If fortran90 you would just do:

do 10 k=1,2
do 20 i=1,3

read(*,*)(a(i,j,k),j=1,3)

20 continue
10 continue

How would the python equivalent go ?

Well, I don't know if this qualifies as equivalent:

=====
from __future__ import with_statement
from functools import partial
from itertools import islice
from pprint import pprint


def read_group(lines, count):
return [map(int, s.split()) for s in islice(lines, count)]


def main():
result = list()

with open('test.txt') as lines:
#
# Filter empty lines.
#
lines = (line for line in lines if line.strip())
#
# Read groups until end of file.
#
result = list(iter(partial(read_group, lines, 3), list()))

pprint(result, width=30)


if __name__ == '__main__':
main()
=====

The output is:

[[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]]

`k` is the first index here, not the last and the code doesn't use fixed
values for the ranges of `i`, `j`, and `k`, in fact it doesn't use index
variables at all but simply reads what's in the file. Only the group
length is hard coded in the source code.

Ciao,
Marc 'BlackJack' Rintsch
.



Relevant Pages

  • Re: @decorator syntax is sugar, but for what exactly?
    ... >> Okay, I will. ... I think that f is a function bound by def (or an ... either in the source code or the library ... actual function bound by def. ...
    (comp.lang.python)
  • Re: noob question: "TypeError" wrong number of args
    ... better understanding of Python's object model. ... def method: ... Python source code and outputs the same source code with only one change: ...
    (comp.lang.python)
  • Re: Ruby Compressor (little long)
    ... have every right to the source code, but when it is installed we do ... def require ... fp = File.join(path, fname) ... # write header data - fname, ...
    (comp.lang.ruby)
  • Re: Python-Help ( Mean,Median & Mode)
    ... It was doing great but I'm having problem listing ... The source code and the output below: ... def input_numbers: ... you don't have any code for computing the median. ...
    (comp.lang.python)
  • Re: noob question: "TypeError" wrong number of args
    ... This has to be in a class statement - else it's shouldn't be touched. ... Python source code and outputs the same source code with only one change: ... insert the string 'self" as the first parameter of every "def ... still prefer to keep consistency in functions definitions. ...
    (comp.lang.python)