python - 使用函数值访问 python dict

标签 python function dictionary

我正在尝试在 python 中制作一个选项菜单,如果用户选择一个数字,则会执行不同的功能:

def options(x):
    return {
        1: f1(),
        2: f2()
    }[x]

def f1():
    print "hi"

def f2():
    print "bye"

不过,我叫好了

options(1)

我得到:

hi
bye

当我调用 options(2)

时也是如此

这是怎么回事?

最佳答案

您正在调用函数而不是将它们分配给键

def f1():
  print "hi"

def f2():
  print "bye"

functions = {1: f1, 2: f2}  # dict of functions (Note: no parenthesis)

def options(x):
    return functions[x]()   # Get the function against the index and invoke it

options(1)
# hi

options(2)
# bye

关于python - 使用函数值访问 python dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22199417/

相关文章:

JSON 字典对象到 Swift 中的字符串

python - 使用 Selenium 在 div 中进行内容搜索的问题

Python:matplotlib - 黑白散点图

Python:使用 wmi 远程启动可执行文件

function - 随机函数怎么可能是真正随机的呢?

以 HashSet<int> 作为值的 c# 字典得到所有的交集

python - Discord Python - 如何从用户 ID 获取用户名?

php - 在所有函数中都有一个 return 语句是好的编程习惯吗?

javascript - OnClick if 语句只运行一次?

objective-c - 如何获取在 objective-c 中单击的 UIButtonTypeDetailDisclosure 注释?