1

Is it possible to write an "if statement" into a lambda functions in python? I am trying to write something along these lines but I am getting a syntax error after the if statement:

filt_sin = snf.generic_filter(lambda x: np.std(sin, (size, size) if x<=sin_std), sin, size=size, mode="nearest")
Samwise
  • 68,105
  • 3
  • 30
  • 44
Eimilems
  • 21
  • 1
  • It is possible, but not in the way you did it. What do you want your `if` to do exactly ? What should it do if `x>sin_std` ? – Mateo Vial Feb 26 '22 at 02:20
  • If x>sin_std for a given (size, size) array I don't want that filter to operate in that section. I want the filter to "move on" to the next (size, size) array. – Eimilems Feb 26 '22 at 02:25
  • So what do you want your lambda function to return in that case ? That's my question. `sin_std` is a variable defined outside all of that ? And what's `snf.generic_filter`? – Mateo Vial Feb 26 '22 at 02:27
  • I have edited the statement to read: filt_sin = snf.generic_filter(sin, lambda x: (np.sum(sin(x) * window) / np.sum(window)) if np.std(x) <= sin_std else sin(x), size=ws, mode="nearest") But now I am getting an exit code -107374157. I believe this is a stack overflow error, any advice on how to over come this? – Eimilems Feb 27 '22 at 22:09

1 Answers1

2

The thing to understand is that whatever single expression is to the right of the : is what your lambda function will return. If you want your lambda to return None under certain conditions, you can use a ternary expression, e.g.:

lambda x: foo(x) if x > y else None

Keywords like if: ... else: ... and for ... in ...: that introduce indented blocks do not work within the scope of a lambda definition, but you can use ternary expressions, generator expressions, etc.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • I have edited the statement to read: filt_sin = snf.generic_filter(sin, lambda x: (np.sum(sin(x) * window) / np.sum(window)) if np.std(x) <= sin_std else sin(x), size=ws, mode="nearest") But now I am getting an exit code -107374157. I believe this is a stack overflow error, any advice on how to over come this? – Eimilems Feb 27 '22 at 22:12