简体   繁体   English

python-从列表项中调用函数

[英]python - call a function from a list item

I want to call a function named in the dictionary depending on the key called. 我想根据所调用的键来调用字典中命名的函数。

Example: 例:

start_options = {'left': 'octopus', 'right': 'lion', 'small': 'pit', 'small door': 'pit'}

choice = raw_input("What do you want to do? ").lower()
        if choice in dictionary:
            print "found: " + choice, start_options[choice]
            print "You chose " + choice
            #code here will call function

def octopus():
    #do something

If you define the functions beforehand, you can then refer to them directly in your dictionary as opposed to string representations: 如果事先定义了函数,则可以直接在字典中引用它们,而不是使用字符串表示形式:

def yada():
    print("Yada!")

def blah():
    print("Blah!")

start_options = {'test1': yada, 'test2': blah}
start_options['test1']()

Running this code produces: 运行此代码将产生:

Yada! 亚达!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM