1 | """ |
---|
2 | listManipulator.py |
---|
3 | =================== |
---|
4 | |
---|
5 | A container module for RecursiveListManipulator classes that transform |
---|
6 | arrays into multi-dimensional list objects. Wrapper functions are |
---|
7 | provided to call these directly as functions. |
---|
8 | |
---|
9 | """ |
---|
10 | |
---|
11 | def recursiveListPopulator(inlist, array, dimlist): |
---|
12 | """ |
---|
13 | Function wrapper around class method RecursiveListManipulator().populator(). |
---|
14 | """ |
---|
15 | return RecursiveListManipulator().populator(inlist, array, dimlist) |
---|
16 | |
---|
17 | def recursiveListWriter(inlist, dimlist, floatFormat="%s"): |
---|
18 | """ |
---|
19 | Function wrapper around class method RecursiveListManipulator().writeLines(). |
---|
20 | """ |
---|
21 | return RecursiveListManipulator().writeLines(inlist, dimlist, floatFormat) |
---|
22 | |
---|
23 | |
---|
24 | class RecursiveListManipulator: |
---|
25 | |
---|
26 | """ |
---|
27 | Methods to convert a 1-D array into a multi-dimensional list. |
---|
28 | """ |
---|
29 | |
---|
30 | def populator(self, inlist, array, dimlist): |
---|
31 | """ |
---|
32 | Populates the list object 'inlist' (e.g. []) with sublists of |
---|
33 | dimensionality defined in the 'dimlist' list of dimensions (e.g [181, 360]). |
---|
34 | At the deepest level it then inserts values from the long list |
---|
35 | 'array'. |
---|
36 | """ |
---|
37 | |
---|
38 | if not hasattr(self, "_counter"): |
---|
39 | self._counter=0 |
---|
40 | if len(dimlist[1:])>0: |
---|
41 | for i in range(dimlist[0]): |
---|
42 | inlist.append([]) |
---|
43 | self.populator(inlist[i], array, dimlist[1:]) |
---|
44 | else: |
---|
45 | count=self._counter |
---|
46 | self._counter=self._counter+dimlist[0] |
---|
47 | endcount=self._counter |
---|
48 | for i in range(count, endcount): |
---|
49 | inlist.append(array[i]) |
---|
50 | return inlist |
---|
51 | |
---|
52 | def writeLines(self, inlist, dimlist, floatFormat="%s"): |
---|
53 | """ |
---|
54 | Method to walk through all the levels of the multi-level list object |
---|
55 | 'inlist' and writes out appropriate values to a list of lines called |
---|
56 | 'self.rtlines'. 'dimlist' is a list of the dimensions within 'inlist'. |
---|
57 | """ |
---|
58 | if not hasattr(self, "rtlines"): |
---|
59 | self.rtlines=[] |
---|
60 | if len(dimlist[1:])>0: |
---|
61 | for i in range(dimlist[0]): |
---|
62 | self.writeLines(inlist[i], dimlist[1:], floatFormat) |
---|
63 | else: |
---|
64 | var_string="" |
---|
65 | for i in range(dimlist[0]): |
---|
66 | var_string=var_string+((floatFormat+" ") % inlist[i]) |
---|
67 | self.rtlines.append("%s\n" % var_string.rstrip()) |
---|
68 | return self.rtlines |
---|
69 | |
---|