[Tutor] increment a counter inside generator
Abhishek Pratap
abhishek.vit at gmail.com
Wed Mar 13 22:15:48 CET 2013
On Wed, Mar 13, 2013 at 2:08 PM, Dave Angel <davea at davea.name> wrote:
> 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
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
Thanks Dave. That probably is the reason why I am getting the error.
-Abhi
More information about the Tutor
mailing list