On 14/03/13 08:12, Abhishek Pratap wrote:

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
[...]
I just used a very contrived example to ask if we can increment a
counter inside a generator. The real case is more specific and
dependent on other code and not necessarily useful for the question.

Not everything can happen inside a list comprehension or generator 
comprehension.
They are both deliberately kept simple, and can only include an expression.

Since count += 1 is not an expression, you cannot use it directly inside a list 
comp. Some possible solutions:

1) wrap it in a helper function:

count = 0

def incr():
    global count
    count += 1

values = [incr() or expr for num in np.random.random_integers(1, 100, 20) if num 
> 20]


2) Use a for loop:

count = 0
for num in np.random.random_integers(1, 100, 20):
    if num > 20:
        count += 1

3) Use len:

values = [num for num in np.random.random_integers(1, 100, 20) if num > 20]
# or if you prefer:
# values = filter(lambda x: x > 20, np.random.random_integers(1, 100, 20))

count = len(values)



4) Use sum:

count = sum(1 for num in np.random.random_integers(1, 100, 20) if num > 20)



--
Steven
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to