Iterating over the cells of an array?

Duncan Smith buzzard at urubu.freeserve.co.uk
Sat May 11 10:53:16 EDT 2002


I am interested in the options for handling the following situation.  I want
to iterate over the cells in a Numeric array.  No problem if the rank is
fixed.  eg.

>>> import Numeric
>>> a = Numeric.array([[1,2,3],[4,5,6]])
>>> s = a.shape
>>> for i in range(s[0]):
...  for j in range(s[1]):
...   print a[i,j]
...
1
2
etc.
>>>

But I'm not sure of the 'best' way to handle this for an array of arbitray
rank (i.e. where 's' is an arbitrary length sequence of non-negative
integers).  (I've just started using 2.2.1, so I haven't sussed iterators
yet.)

I'm sure I can come up with some hack.  But I'm trying to improve my
programming style.  So, anyone any thoughts on this?  Do iterators offer a
cute way of handling it?  Cheers.  TIA.

Duncan Smith

p.s. For one specific problem I will be dealing with very sparse arrays, and
I only really want to consider the cells with non-zero values.  So any
problem-specific advice would also be appreciated.  (In this case I would
need to return both the value and index of the cell.) :-)







More information about the Python-list mailing list