[python笔记]switch&case in python

.Switch & case

转载来自:http://vifix.cn/blog/python%E7%9A%84switchcase%E8%AF%AD%E6%B3%95.html

Python没有switch…case的语法,不过可以用Dictionary和lambda匿名函数的特性来写出同样优雅的代码,比如这段javascript代码:

switch(value){
    case 1:
        func1();
        break;
    case 2:
        func2();
        break;
    case 3:
        func3();
        break;
}

等价的Python代码:

{
  1: lambda: func1,
  2: lambda: func2,
  3: lambda: func3
}[value]()

 

带赋值的情况:

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

用try…catch来实现带Default的情况,不过这个形式就感觉差些了:

try:
    {'option1': func1,
     'option2': func2,
     'option3': func3}[value]()
except KeyError:
    # default action

 # end of switch & case

 

.Dictionary Sort

  I.dictionary Sort by Value.   #!default by ASC.

   for key, value in sorted(dict.iteritems(), key=lambda (k,v) : v ) : 
     print key, value

  #k and v in (k,v) for represent dict's item's paras,  and the last v is telling the system to sorted by it.

 II.Sort by Key.

   for key, value in sorted(dict.iteritems(), key=lambda (k,v) : k ) :
     print key, value

   OR 

   for key in sorted(dict.iterkeys()):      print key, dict[key]

  Example:

  >>> dict = {'mark':60, 'jimmy':80, 'tommy':70}          
  >>> for key, value in sorted(dict.iteritems(), key=lambda (k,v) : v ) :
  ...     print key, value                     
  ...                              
  mark 60                           
  tommy 70                          
  jimmy 80                          

  >>> for key, value in sorted(dict.iteritems(),key = lambda (k,v): k):
  ...     print key,value                      
  ...                              
  jimmy 80                           
  mark 60                           
  tommy 70

 

  Other. Sort List with dict.

    dict= [ {'id':0, 'value':9}, {'id':1, 'value':100}, {'id':5, 'value':99}]

    d.sort(key=lambda x:x['id']) #sort by id

    d.sort(key=lambda x:x['value']) #sort by value

 

#End of Dictionary Sort

posted @ 2012-06-24 20:23  叫我学徒  阅读(1289)  评论(0编辑  收藏  举报