Using a dictionary to select function to execute

前端 未结 10 2100
走了就别回头了
走了就别回头了 2020-11-27 13:05

I am trying to use functional programming to create a dictionary containing a key and a function to execute:

myDict={}
myItems=(\"P1\",\"P2\",\"P3\",....\"         


        
10条回答
  •  情歌与酒
    2020-11-27 13:52

    # index dictionary by list of key names
    
    def fn1():
        print "One"
    
    def fn2():
        print "Two"
    
    def fn3():
        print "Three"
    
    fndict = {"A": fn1, "B": fn2, "C": fn3}
    
    keynames = ["A", "B", "C"]
    
    fndict[keynames[1]]()
    
    # keynames[1] = "B", so output of this code is
    
    # Two
    

提交回复
热议问题