Python notes: Dictionary and anonymous Functions (lambda) for alternative case statements

Source: Internet
Author: User
Tags case statement

In the Linux shell we are accustomed to use case statements to do branch processing, but Python omitted this function, after a multi-party search, found that in fact, the case statement in the C language by looking at the corresponding hash table, to jump. We can do this in Python in three ways. 1, dictionary, 2, lambda;3, switch class.

1. Dictionaries

dictcase={' case1 ': func1, ' case2 ': func2 .... ' CaseN ': FuncN}

#注意字典中对应的是函数名, no parentheses.

Use the Get function of the dictionary when calling to implement the default option:

Dictcase.get (Casen,default_func) ()


2. anonymous function lambda

Common examples on the Web:

result = {
' A ': Lambda x:x * 5,
' B ': Lambda x:x + 7,
' C ': Lambda x:x-2
}[value] (x)

I don't know much about ...

def a (s): Print sdef switch (CH): try: {' 1 ': lambda:a ("one"), ' 2 ': lambda:a ("one"), ' 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

This example is good, but the total sense of this is not very good, no dictionary flexible.

My own example:

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 g =lambda x:x #m =sys.argv[1] #n =sys.argv[2] #print m,n m=input ("functionname:") N=input ("number:") try : (m) (n) except:20 print "Function not exists:{f1,b}" 21# using a try to implement the default function

3. Install switch class: Https://pypi.python.org/pypi/switch/1.1.0#downloads

With the first two, installing this class is a bit boring ...

# -*- coding: utf-8 -*-from __future__ import with_statement__version__  =  ' 1.1.0 ' __all__ = [' cswitch ',  ' Switch ']import reclass 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&nbSp;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&nbsP;   def _check_finished (self):        if  self._matched_case is true and self._fall_through is false:             raise self. Stopexecutionclass 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)


This article is from the "Hiubuntu" blog, make sure to keep this source http://qujunorz.blog.51cto.com/6378776/1538985

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.