C/C++程序员习惯用switch语句,但python是没有的。那么python如何处理多分支情况呢?方法一是使用if--elif--elif--else,显然分支越多,判断越多,不是最优;那么下面介绍最优的方法二——使用字典映射来实现switch/case方法。
>>> #-*- coding: utf-8 -*-
>>> import time
>>> now = time.localtime()
>>> print now
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=10, tm_hour=10, tm_min=38, tm_sec=43, tm_wday=6, tm_yday=253, tm_isdst=0)
>>> print time.strftime('%Y-%m-%d %H:%M:%S',now)
2017-09-10 10:38:43
>>> def long_time_cn(t):
print time.strftime('%Y-%m-%d %H:%M:%S',t)
>>> def long_time_en(t):
print time.strftime('%B %d %Y %H:%M:%S',t)
>>> def short_time_cn(t):
print time.strftime('%y-%#m-%#d %#H:%#M',t)
>>> def short_time_en(t):
print time.strftime('%b %#d %y %#H:%#M',t)
>>> timelist = {
'cnl':long_time_cn,
'enl':long_time_en,
'cns':short_time_cn,
'ens':short_time_en
}
>>> def mytime(outputmothod,outputtime):
try:
t = timelist.get(outputmothod)(outputtime)
return t
except Exception,e:
print '%s' %(e)
>>> mytime('cnl',now)
2017-09-10 10:38:43
>>> mytime('cns',now)
17-9-10 10:38
>>> mytime('ens',now)
Sep 10 17 10:38
>>> mytime('enl',now)
September 10 2017 10:38:43
>>> mytime('ennnn',now)
'NoneType' object is not callable
>>> mytime(1,now)
'NoneType' object is not callable
>>>