Returns "hoge" when 0 comes in as an argument A function that just returns the input value when anything else comes. I also wrote the detailed procedure below.
As I often get lost, it is a memorandum.
def x(value):
if value == 0:
return "hoge"
else:
return value
This is
y = lambda value : "hoge" if value == 0 else value
It will be like this.
Expressed in letters:
(Function name) = lambda (argument) : (Value to return if the condition is True) if (conditions) else (conditionsがFalseなら返す値)
If you look at this at first glance, you will not understand it.
The lambda function is Because the function you want to change must be a one-line function First, put the following if statement on one line.
#Reprint
def x(value):
if value == 0:
return "hoge"
else:
return value
def x(value):
if value == 0
def x(value):
"hoge" if value == 0
def x(value):
"hoge" if value == 0 else value
This succeeded in making the if statement into one sentence. Then put the function on one line.
↓ 3 things you don't need 1, def 2, function name → x 3, parentheses surrounding the argument → ()
value :
"hoge" if value == 0 else value
When the lines are aligned
value : "hoge" if value == 0 else value
You can do this. It's getting closer and closer.
Let's make it a lambda function. Write lambda at the beginning
lambda value : "hoge" if value == 0 else value
Substitute for x. (x is the function name)
x = lambda value : "hoge" if value == 0 else value
That's all there is to it.
x(0)
>>> 'hoge'
x(100)
>>> 100
that's all.
Recommended Posts