[Numpy-discussion] Can you enumerarte an array?
Arnd Baecker
arnd.baecker at web.de
Wed Oct 12 06:06:45 CDT 2005
Hi Chris,
On Mon, 10 Oct 2005, Chris Barker wrote:
> Travis Oliphant wrote:
> > All flavors of Numeric would return
> >
> > 0 a[0]
> > 1 a[1]
> > .
> > .
> > .
> > n-1 a[n-1]
> >
> > where n=a.shape[0]
> >
> > in response to index, item in enumerate(A):
>
> Right, as expected, and as Anrd pointed out, this is useful behaviour.
>
> > In scipy you could also get
> >
> > 0 a.flat[0]
> > 1 a.flat[1]
>
> I do like the new flat!
>
> > To do something like he wants, I think we would have to construct a
> > different iterator then enumerate.
>
> Exactly,. I didn't mean to imply that that's what the built-in enumerate
> should do.
>
> > It wouldn't be that hard using the
> > a.flat iterator (it's just a remapping of the 1-d index).
>
> Cool. then again, consider this a feature request, for a nd_enumerate,
> or whatever you want to call it.
>
> I'm sorry that implimenting something like this myself is way out my depth!
Below is one way to do it. BUT:
- it is the first iterator I ever wrote...
- it is not using yield, which might be better style -
Oh and indeed it does give nicer code (see example 1).
- it does not use a.flat.
(BTW: I found
http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf
helpful)
Best,
Arnd
1) Short variant
----------------
from Numeric import *
def arr_enumerate(arr):
for indy in xrange(arr.shape[1]):
for indx in xrange(arr.shape[0]):
yield (indy,indx),arr[indy,indx]
if __name__=="__main__":
x=reshape(arange(25),(5,5))
print x
for ind,value in arr_enumerate(x):
print ind,value
2) Longer variant (just left in for historical reasons ...;-)
-------------------------------------------------------------
from Numeric import *
class arr_enumerate:
def __init__(self,arr):
self.Nx,self.Ny=arr.shape # just assume 2D here
self.arr=arr
self.indx=0
self.indy=0
def next(self):
indx=self.indx
indy=self.indy
self.indx+=1
if self.indx==self.Nx:
self.indx=0
self.indy+=1
if self.indy==self.Ny and self.indx==1:
raise StopIteration
return (indy,indx),self.arr[indy,indx]
def __iter__(self):
return self
if __name__=="__main__":
x=reshape(arange(25),(5,5))
print x
for ind,value in arr_enumerate(x):
print ind,value
######################################
More information about the Numpy-discussion
mailing list