使用函数值访问python dict

2024-04-20 07:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python中创建一个选项菜单,如果用户选择一个数字,将执行一个不同的函数:

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

def f1():
    print "hi"

def f2():
    print "bye"

不过,我打电话给你

options(1)

我得到:

hi
bye

当我调用options(2)时也是如此

怎么回事?你知道吗


Tags: 函数用户returndef选项菜单数字hi
3条回答

您正在调用函数,而不是根据键来分配它们

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

您的字典是用函数的返回值构建的;在从dict中选取函数之前,不要调用该函数:

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

现在,您只需存储字典中函数的引用,并在检索后调用所选函数。你知道吗

演示:

>>> def f1():
...     print "hi"
... 
>>> def f2():
...     print "bye"
... 
>>> def options(x):
...     return {
...         1: f1,
...         2: f2
...     }[x]()
... 
>>> options(1)
hi
>>> options(2)
bye

用return替换print,用return替换return,这样就可以了。或者使用第四版。你知道吗

相关问题 更多 >