In NumPy, whole segments of arrays can be assigned using : as a wildcard for index ranges. For example:
>>> (n, m) = (5,5)
>>> a = numpy.array([[0 for i in range(m)] for j in range(n)])
>>> a
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
>>> for i in range(n):
... a[i, :] = [1 for j in range(m)]
>>> a
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
However, numpy.array only holds numeric data. I need an array type which can hold arbitrary objects and can be addressed like NumPy arrays. What should I use?
EDIT: I’d like the full flexibility of this range assignment syntax, e.g. this should work, too:
>>> a[:,1] = 42
>>> a
array([[ 1, 42, 1, 1, 1],
[ 1, 42, 1, 1, 1],
[ 1, 42, 1, 1, 1],
[ 1, 42, 1, 1, 1],
[ 1, 42, 1, 1, 1]])
Maybe I’m missing something here but numpy does in fact hold objects as well as numbers.
When you place complex objects into a numpy array the
dtypebecomesobject. You can access members and slices of the array as you would with normal numpy arrays. I’m not familiar with the serialization but you may experience drawbacks in that area.If you are convinced that numpys are not the way to go a standard Python list is a great way to maintain a collection of objects and you may also slice the python list the very similar to the numpy array.