efficent test for array with only one value?
David M. Cooke
cookedm+news at physics.mcmaster.ca
Tue Jan 20 16:06:17 EST 2004
At some point, Kyler Laird <Kyler at news.Lairds.org> wrote:
> Robert Kern <rkern at ucsd.edu> writes:
>
>>However, alltrue(a.flat == a.flat[0]) will work but won't short-circuit.
>
> How did I miss that?! Yes, that's the kind of operation I sought.
> I'm surprised that it doesn't short-circuit. It *should*, right?
>
> It's a shame that it only works along a single axis. The use of
> "flat" is a problem for me. I'm looking at sections of an image
> (building a quadtree) so the arrays I'm checking are not contiguous.
> I think that means I have to resort to something ugly like this.
> Numeric.alltrue(Numeric.alltrue(a == a[0,0]))
> That eliminates many opportunities for short-circuiting.
>
> I can also flatten the array using reshape() before checking it. I
> assume that also means a lot of possibly unnecessary operations.
> (Does reshape() return a copy of the array or just an array with
> the original data and a new shape?)
In general, use ravel() instead of .flat.
ravel() is a simple wrapper around reshape(), which will make a
contiguous only if necessary. .flat will fail for non-contiguous arrays
(like views into another array).
--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
More information about the Python-list
mailing list