python避免if-else过多的办法

2020-01-06 11:12:52 浏览数 (1)

方法一:来自http://biancheng.dnbcw.net/python/417264.html

代码语言:javascript复制
while True:
    n = raw_input()
    i = int(n) % 10
    if i == 0:
        print 0
    elif i == 1:
        print 1
    elif i == 2:
        print 2
    elif i == 3:
        print 3

用Function Map可以这样写:

代码语言:javascript复制
def get0():
    print 0
def get1():
    print 1
def get2():
    print 2
def get3():
    print 3


dict = {0:get0, 1:get1, 2:get2, 3:get3}

while True:
    n = raw_input()
    i = int(n) % 10
    dict[i]()              

0 人点赞