[PYTHON] Easily write if-elif with lambda

Python does not have the so-called switch syntax. This makes it easier to understand because each evaluation formula is close to each other, but it inevitably becomes redundant.

for a in range(3):
    if a == 0:
        print "Hello!!"
    elif a == 1:
        print "How are you?"
    elif a == 2:
        print "Good Bye :)"

Although it is readable, I think that writing "a =" a ==" would be a hassle. So, when I thought that I wish I could write it a little easier, I thought that there was lambda, so I will use it for a while.

for a in range(3):
    case = lambda check_num: a == check_num
    if case(0):
        print "Hello!!"
    elif case(1):
        print "How are you?"
    elif case(2):
        print "Good Bye :)"

Then, it will output the same output as the first one. However, the disadvantage in this example is

However, when comparing the same variables, rather than writing an expression one by one, wrapping it in lambda and using that function made if quite neat and convenient, so make a note here. I will do it.

Recommended Posts

Easily write if-elif with lambda
Let's write class __str__ more easily using lambda!
Make Lambda Layers with Lambda
Easily daemonized with Supervisor
Easily beep with python
Write multiple records to DynamoDB with Lambda (Python, JavaScript)
Operate TwitterBot with Lambda, Python
Easily write JSON and Python dataclass conversions with quicktype and dacite
Deploy Django serverless with Lambda
Let's write python with cinema4d.
Easily build CNN with Keras
AWS Lambda with PyTorch [Lambda import]
Dynamically move Amplify with Lambda
Write to csv with Python
Write flexible unittests with PyHamcrest!
Easily cProfile with a decorator
[Python] Write to csv file with Python
[AWS] Create API with API Gateway + Lambda
Easily implement subcommands with python click
Face detection with Lambda (Python) + Rekognition
Easily handle lists with python + sqlite3
Write AWS Lambda function in Python
Easily switch pyenv virtualenvs with peco
Write a Residual Network with TFLearn
Write FW to TWE-Lite with TWE-Lite R.
Using Lambda with AWS Amplify with Go
Easily handle databases with Python (SQLite3)
Easily build virtual machines with Vagrant
[Python] Collect images easily with icrawler!
Notify HipChat with AWS Lambda (Python)
Easily post to twitter with Python 3
Write Reversi AI with Keras + DQN
Use PostgreSQL with Lambda (Python + psycopg2)
Write a stacked histogram with matplotlib
Easily send emails with Gmail with Django
Easily draw a map with matplotlib.basemap
Write a batch script with Python3.5 ~