[SciPy-user] what is simpliest way to create this boolean array

Stefan van der Walt stefan@sun.ac...
Thu Aug 30 06:21:41 CDT 2007


On Thu, Aug 30, 2007 at 01:14:37PM +0200, Stefan van der Walt wrote:
> On Thu, Aug 30, 2007 at 09:33:29PM +1200, Angus McMorland wrote:
> > On 30/08/2007, dmitrey <openopt@ukr.net> wrote:
> > > No, I meant a = array((True, True, ... True (m1 numbers), False,
> > > False,... False(m2 numbers), True, ...(m3 numbers), False, ...(m4
> > > numbers) ))
> > 
> > Of course, that makes more sense. A cool generic list comprehension solution is:
> > 
> > def make_bool(*args):
> >     a = []
> >     [[a.append(k) for k in [not bool((i % 2)) for y in xrange(x)]] for
> > i, x in enumerate(args)]
> >     return a
> > 
> > Still slightly faster than the numpy way (by ~25% I think).
> 
> Or with only one for-loop:
> 
> a = []
> for i,x in enumerate(m):
>     a.extend([i%2]*x)
> return ~N.array(a,bool)
> 
> where m contains [m1,m2,m3].

Or without any for-loops!

x = N.ones(len(m),bool)
x[1::2] = False
x.repeat(m)

Cheers
Stéfan


More information about the SciPy-user mailing list