[英]python - call a function from a list item
我想根据所调用的键来调用字典中命名的函数。
例:
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
如果事先定义了函数,则可以直接在字典中引用它们,而不是使用字符串表示形式:
def yada():
print("Yada!")
def blah():
print("Blah!")
start_options = {'test1': yada, 'test2': blah}
start_options['test1']()
运行此代码将产生:
亚达!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.