Get the App
SLTechnology News&Howtos  ›  Database  › 

How to realize switch case function by using Dictionary and function in python

Shulou Source: shulou.com Published: 2022-05-31 16:07:12 11月28日 Update

Python how to use dictionaries and functions to achieve switch case function, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Python does not have the syntax of switch-case, such as Cumberbatch grammar, Java, etc. However, this feature, such as Dictionary and lambda anonymous function features, is used to replace the implementation.

Dictionary + function realizes four operations in switch mode: (operators in switch only need to be judged once, which is different from if and elsif judgment)

Law 1:

-- Code

[root@bigdata01 ~] # cat t1.py

#! / usr/bin/python

# coding:utf-8

Def add (XBI y):

Return Xeroy

Def sub (XBI y):

Return Xmury

Def mul (XBI y):

Return Xeroy

Def div (XBI y):

Return x/y

Operator = {"+": add, "-": sub, "*": mul, "/": div}

Def f (XMagneol y):

Print operator.get (o) (xQuery y)

F (2, "+", 2)

F (2,-", 2)

F (2, "*", 2)

F (2, / ", 2)

-- Operation

[root@bigdata01 ~] # python t1.py

four

0

four

one

Law 2:

-- Code

[root@bigdata01 ~] # cat t2.py

Def calc (type,x,y):

Calculation = {'+': lambda: X

'*': lambda:x-y

'-': lambda:x*y

'/': lambda:x/y}

Return calculation [type] ()

Result1 = calc ('+', 3pm 6)

Result2 = calc ('-', 3pm 6)

Result3 = calc ('*', 3pm 6)

Result4 = calc ('/', 3pm 6)

Print result1

Print result2

Print result3

Print result4

-- Operation

[root@bigdata01 ~] # python t2.py

nine

eighteen

-3

0

Using key > in python dictionary is equivalent to value call corresponding function in switch,python dictionary in other languages > equivalent to case in other languages.

After reading the above, have you mastered how python uses dictionaries and functions to achieve switch case functions? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Function dictionary function code content situation method more language problem operation operation helplessness for this four operations reasons four skills patterns Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Information Linux Shulou Technology macOS