zoukankan      html  css  js  c++  java
  • Python_Tips[1] -> 利用 Python 的字典实现 Switch 功能

    利用 Python 的字典实现 Switch 功能


    Python是没有switch语句的,当遇到需要实现switch语句的功能时,一般可以用if/else进行代替,但是还有一种更加简洁的实现方法,利用字典进行实现,将需要选择的条件设为字典的键,选择的结果设为值,通过字典键索取值的方式实现switch的功能。

     1 def hello():
     2     print('Hello!')
     3 
     4 def world():
     5     print('World!')
     6 
     7 d = {'Hello': hello,
     8      'World': world}
     9 
    10 def foo(case):
    11     return d[case]
    12 
    13 foo('Hello')()
    14 foo('World')()

    代码运行结果

    Hello!
    World!

    使用字典实现了与 Switch 类似的功能。

  • 相关阅读:
    python
    突然萌发关于 redis 的想法(1)
    Liunx
    Git
    说一下数据库查询 和 分页问题的解决
    易忘点
    python
    python
    python
    python
  • 原文地址:https://www.cnblogs.com/stacklike/p/8202776.html
Copyright © 2011-2022 走看看