Entry
Two-dimensional arrays
Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 128, David Ascher
"""
Packages: basic_applications.arrays
"""
"""
> I have a problem that needs two-dimensional arrays, but NumPy really seems
> like overkill. I had solved it another way, then realized I really
> *needed* two-dimensional arrays.
Here's a little something based, as was suggested, on a list of arrays.
It's incomplete, but it should be a start -- while it only deals with
'single-attribute arrays', it shouldn't be too hard to make a
"multiattributemat' which builds on Mat to deal w/ multivalued arrays.
"""
"""
usage:
x = Mat((10,10), 'i')
x[0] = [4]*10
x[1][4:10] = x[0][:6]
x[2] = x[0]
etc.
"""
from array import array
import string
class Mat:
defaults = {}
for d in ('bBhHiIlLfd'): defaults[d] = 0.0
defaults['c'] = ' '
def __init__(self, (width, height), typecode, default=None):
assert Mat.defaults.has_key(typecode)
self.rows = [None]*height
self.width = width
self.height = height
self.typecode = typecode
for i in range(height):
if default is None:
init = [Mat.defaults[typecode]]*width
else:
if type(default) in (type(()), type([])):
assert len(default) == width
init = default
else:
init = default*width
self.rows[i] = array(typecode, init)
def __getslice__(self, start, end):
return self.rows[start:end]
def __getitem__(self, item):
if type(item) == type(()):
assert len(item) == 2
i,j = item
return self.rows[i][j]
elif type(item) == type(0):
return self.rows[item] # shared reference!
elif type(item) == type(slice(0,1,1)):
# deal with extended slices
raise "Unimplemented"
def __setitem__(self, item, value):
if type(item) == type(()):
assert len(item) == 2
i,j = item
self.rows[i][j] = value
elif type(item) == type(0):
assert len(value) == self.width
value = list(value)
self.rows[item] = array(self.typecode, value)
elif type(item) == type(slice(0,1,1)):
# deal with extended slices
raise "Unimplemented"
def __repr__(self):
rows = []
for r in self.rows:
rows.append(str(r)[len("array('i', "):-1])
return string.join(rows, ',\n')
x = Mat((10,10), 'i')
print x