[Tutor] increment a counter inside generator
Dave Angel
davea at davea.name
Wed Mar 13 22:08:47 CET 2013
On 03/13/2013 03:50 PM, Abhishek Pratap wrote:
> Hey Guys
>
> I might be missing something obvious here.
>
>
> import numpy as np
>
> count = 0
> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20]
>
> File "<ipython-input-45-0ba0e51b7644>", line 2
> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20]
> ^
> SyntaxError: invalid syntax
>
>
> Also tried
> <Missing rest of message>
I can't help with the numpy portion of that, but that's not the correct
syntax for a list comprehension. The first item must be an expression,
and count+=1 is NOT.
You probably want (untested)
count = sum([ 1 for num in ......])
which will add a bunch of ones. That will probably give you a count of
how many of the random integers are > 20.
There also may very well be a function in numpy that would do it in one
step. See Oscar's message.
--
DaveA
More information about the Tutor
mailing list