'Creating an If statement within a lumbda function [duplicate]
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")
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
