python list/array question...
Vic.Kelson at gmail.com
Vic.Kelson at gmail.com
Thu Jul 6 10:15:54 EDT 2006
Another way to do it is using a dict with keys that are tuples:
>>> arr = {}
>>> arr[0,0] = 'a1'
>>> arr[0,1] = 'a2'
>>> arr[1,0] = 'b1'
>>> arr[1,1] = 'b2'
>>> arr[2,0] = 'c1'
>>> arr[2,1] = 'c2'
>>> for j in range(3):
... for i in range(2):
... print arr[j,i], ' ',
... print
...
a1 a2
b1 b2
c1 c2
>>>
You can derive a class from dict that implements desired behaviors
(e.g. bounds checking, nrows and ncols attributes). Using this approach
over lists of lists is nice: old fogey scientific programmers like me
prefer the explicit [j,i] syntax over the [j][i] way, and it's easily
extensible over more than two dimensions ([k][j][i]??? Yikes!). This is
perhaps not preferred for a "full" matrix (I'd tend to use a NumPy
array of Objects), but it can be useful.
I've used it in two cases:
-- A "sparse" matrix (overload dict.__getitem__ to return 0 if the
tuple (j,i) is not a valid key),
-- A "multidimensional array" in which all the indices are strings,
like a table with column labels and row labels (in my case, it was a
3-dimensional "table" with a concatenated key of three text strings but
there were reasons not to use a relational database). It was very
convenient to implement the code in this way, and extremely readable.
This trick is also useful with dbm files, e.g. using shelve.
--vic
More information about the Python-list
mailing list