Python的switch方法

        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
>>> 


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值