Iterating over the cells of an array?

Fernando Pérez fperez528 at yahoo.com
Sun May 12 05:15:13 EDT 2002


<posted & mailed>

Alex Martelli wrote:

>> 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
> 
> for item in Numeric.ravel(whatever):
>     process(item)
> 

I'd instead write:

if myarray.iscontiguous:
  for item in myarray.flat:
    do()
else:
  for item in ravel(myarray):
    do()

unless you know ahead of time that it's never going to be contiguous. ravel is 
I believe a copy operation, much more expensive than a call to the flattened 
array (which simply allows the loop to be done with straight pointer 
arithmetic underneath).

cheers,

f
  



More information about the Python-list mailing list