gpt4 book ai didi

python - 从列表项调用函数

转载 作者:行者123 更新时间:2023-12-01 03:55:14 24 4
gpt4 key购买 nike

我想根据调用的键调用字典中命名的函数。

示例:

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']()

运行此代码会产生:

Yada!

关于python - 从列表项调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37602337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com