python避免if-else过多的办法

发布时间:2019-09-22 07:53:49编辑:auto阅读(2532)

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

    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可以这样写:

    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]()
    方法二:

关键字