Python笔记:替代case语句的字典和匿名函数(lambda)

在linux的shell中我们习惯使用case语句来做分支处理,然而Python中却省略了这个函数,经过多方查找,发现其实case语句在C语言中是通过查对应的hash表,来进行跳转的。在Python中我们可以通过三种方法来实现这种功能。1、字典;2、lambda;3、switch类。

1、字典

dictCase={‘case1‘:func1,‘case2‘:func2....‘caseN‘:funcN}

#注意字典中对应的是函数名,不要圆括号。

在调用的时候使用字典的get函数来实现default选项:

dictCase.get(caseN,default_Func)()

2、匿名函数lambda

网上常见的例子:

result = {  ‘a‘: lambda x: x * 5,  ‘b‘: lambda x: x + 7,  ‘c‘: lambda x: x - 2}[value](x)

看不太懂。。。

def a(s):
    print s
def switch(ch):
    try:
      {‘1‘: lambda : a("one"),
       ‘2‘: lambda : a("two"),
      ‘3‘: lambda : a("three"),
       ‘a‘: lambda : a("Letter a")
      }[ch]()
    except KeyError:
      a("Key not Found")

eg:

>>switch(‘1‘)
one
>>switch(‘a‘)
Letter a
>>switch(‘b‘)
Key not Found

这个例子不错,但总觉的这样不太好看,没字典灵活。

我自己的例子:

  1 #!/usr/bin/env python 
  2 import sys
  3   
  4 def f1(a):
  5   print a
  6           
  7 def b(b):
  8   print b+1
  9 
 10 g=lambda x:x
 11 
 12 #m=sys.argv[1]
 13 #n=sys.argv[2]
 14 #print m,n
 15 m=input("functionname:")
 16 n=input("number:")
 17 try:
 18   g(m)(n)
 19 except:
 20   print "function not exists:{f1,b}"
 21#使用try来实现default函数

3、安装switch类:https://pypi.python.org/pypi/switch/1.1.0#downloads

有了前面两种,安装这个类就有点无聊了。。。

# -*- coding: utf-8 -*-

from __future__ import with_statement

__version__ = ‘1.1.0‘
__all__ = [‘CSwitch‘, ‘Switch‘]

import re

class Switch(object):

    class StopExecution(Exception):
        pass

    def __init__(self, switch_value, fall_through=False):
        self._switch_value = switch_value
        self._default_fall_through = fall_through
        self._fall_through = False
        self._matched_case = False
        self._default_used = False

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type is self.StopExecution

    def __call__(self, case_value, *case_values, **kwargs):
        return self.call(
            lambda switch_value: any(switch_value == v for v in (case_value, ) + case_values),
            **kwargs
        )

    def match(self, match_value, *match_values, **kwargs):
        def test(switch_value):
            # It is safe to call `re.compile()` on a compiled pattern:
            # a=re.compile(‘test‘); assert a is re.compile(a)
            str_switch_value = str(switch_value)
            re_tests = (re.compile(v) for v in (match_value, ) + match_values)
            return any(regex.match(str_switch_value) for regex in re_tests)

        return self.call(test, **kwargs)

    def call(self, test, fall_through=None):
        if self._default_used:
            raise SyntaxError(‘Case after default is prohibited‘)

        self._check_finished()
        if self._fall_through or test(self._switch_value):
            self._matched_case = True
            self._fall_through = fall_through if fall_through is not None else self._default_fall_through
            return True

        return False

    @property
    def default(self):
        self._check_finished()
        self._default_used = True

        return not self._matched_case

    def _check_finished(self):
        if self._matched_case is True and self._fall_through is False:
            raise self.StopExecution

class CSwitch(Switch):
    """
    CSwitch is a shortcut to call Switch(test_value, fall_through=True)
    """
    def __init__(self, switch_value):
        super(CSwitch, self).__init__(switch_value, fall_through=True)

Python笔记:替代case语句的字典和匿名函数(lambda)

时间: 2024-08-04 10:37:28

Python笔记:替代case语句的字典和匿名函数(lambda)的相关文章

Python学习笔记010——匿名函数lambda

1 语法 my_lambda = lambda arg1, arg2 : arg1 + arg2 + 1 arg1.arg2:参数 arg1 + arg2 + 1 :表达式 2 描述 匿名函数不需要return来返回值,表达式本身结果就是返回值. lambda 仅简洁了代码,并不会提高程序运行效率 如果可以用 for...in...if 来完成的,最好不使用匿名函数lambda 使用lambda时,函数内不要包含循环.嵌套:如果存在,则最好使用def函数来完成,这样的代码可读性和复用性均较高 l

python第五天:协程,匿名函数,递归函数,模块导入,re模块

上节回顾 函数对象 函数可以被当成数据来传递 def func(): pass 1.可以被引用.f=fun 2.可以当做参数传递给另外一个函数 3.可以作为函数的返回值 4.可以当做容器类型的元素 比如用户有10多个参数,我们不需要写10多个if判断.可以写一个字典. dic = {'func1':func1,'func2':func2} 调用个时候就用dic['func1']() 函数的嵌套 函数的嵌套可以分为两种:嵌套定义和嵌套调用. 嵌套调用:函数的执行过程中调用其他的函数,可以更加细化的

python的匿名函数lambda解释及用法

lambda函数的语法只包含一个语句,如下:    lambda arg1,arg2,.....argn:expression(主要是看下面的例子)代码示例: #-*- coding:utf-8 -*- #__author__ = "www.iplaypy.com" # 普通python函数 def func(a,b,c): return a+b+c print func(1,2,3) # 返回值为6 # lambda匿名函数 f = lambda a,b,c:a+b+c print

Python递归列出目录中文件脚本及其匿名函数

1.递归列出目录里的文件的脚本举例 列出目录中的文件可以通过下面方法:os.listdir() In [1]: import os In [4]: os.listdir('/root') Out[4]: ['.tcshrc', '.bash_history', '.bashrc', 'ENV', '.cache', '.config', '.cshrc', '.bash_logout', 'python', '.ssh', 'shell', '.bash_profile', '.ipython'

python学习三十三天函数匿名函数lambda用法

python函数匿名函数lambda用法,是在多行语句转换一行语句,有点像三元运算符,只可以表示一些简单运算的,lambda做一些复杂的运算不太可能.分别对比普通函数和匿名函数的区别 1,普通的函数用法 def func(): print('aaa') func() 2,匿名函数的用法 f=lambda x,y:x*y m=f(3,5) print(m) 输出结果 15 匿名比较复杂的用法条件判断,匿名函数一般搭配函数内置函数使用 map() 文章来自(www.96net.com.cn) 原文地

在Python中递归函数调用举例and匿名函数lambda求1~100的和及计算阶乘举例

1.递归列出目录里的文件的脚本举例列出目录中的文件可以通过下面方法:os.listdir() In [1]: import os In [4]: os.listdir('/root') Out[4]: ['.tcshrc', '.bash_history', '.bashrc', 'ENV', '.cache', '.config', '.cshrc', '.bash_logout', 'python', '.ssh', 'shell', '.bash_profile', '.ipython',

python中匿名函数lambda如何用

python中经常用到的一个函数:匿名函数lambda ,什么是匿名函数?匿名函数的意义是什么?匿名函数怎么样用?(疑问三连,what,why,how) 一,什么是匿名函数? python中没有名字的函数,称为匿名函数.语法格式:lambda  x : x**2  既 lambda+形参:代码块 二,匿名函数的意义是什么? 一是它没有名字,所以不会引起命名冲突,二是它格式简单,代码块直接return返回值,比较灵活方便,而且因为没有名字,用完就丢弃了,不占内存. 三,匿名函数怎么用? 这个得举例

python技巧 switch case语句

不同于C语言和SHELL,python中没有switch case语句,关于为什么没有,官方的解释是这样的 使用Python模拟实现的方法: def switch_if(fun, x, y):    if fun == 'add':        return x + y    elif fun == 'sub':        return x - y    elif fun == 'mul':        return x * y    elif fun == 'div':       

Python函数和函数式编程(2): 匿名函数--lambda

原文地址:http://blog.csdn.net/majianfei1023/article/details/45269343 一. lambda函数: lambda函数也叫匿名函数,函数没有具体的名称.先来看一个最简单例子: def f(x): return x * 2 g = lambda x : x * 2 看一下 f 和 g的写法有什么不同,f是定义了一个函数,传进去一个参数x,然后x*2,g是定义了一个lambda,后面跟着一个x(这个就是参数),然后跟着一个 : x * 2 (这就