有没有办法将函数存储在列表或字典中,以便在调用索引(或键)时触发存储的函数?

问题描述 投票:0回答:3

例如,我试过这样的东西,但不起作用:

mydict = {
    'funcList1': [foo(), bar(), goo()],
    'funcList2': [foo(), goo(), bar()]}

是否有某种具有这种功能的结构?

我意识到我显然可以用一堆

def
语句轻松做到这一点:

def func1():
    foo()
    bar()
    goo()

但是我需要的陈述数量变得非常笨重且难以记住。最好将它们很好地包装在一本字典中,我可以不时检查这些键。

python dictionary dispatch
3个回答
154
投票

函数是 Python 中的一流对象,因此您可以使用字典进行分派。例如,如果

foo
bar
是函数,而
dispatcher
是这样的字典。

dispatcher = {'foo': foo, 'bar': bar}

请注意,值是

foo
bar
,它们是函数对象,而不是
foo()
bar()

调用

foo
,你可以做
dispatcher['foo']()

编辑:如果你想运行存储在列表中的多个函数,你可以做这样的事情。

dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}

def fire_all(func_list):
    for f in func_list:
        f()

fire_all(dispatcher['foobar'])

0
投票
# Lets say you have 10 programs or functions:
func_list = [program_001, program_002, program_003, program_004, program_005,
             program_006, program_007, program_008, program_009, program_010]

choose_program = int(input('Please Choose a program: ')) # input function number

func_list[choose_program - 1]()  

0
投票

案例 1:没有参数。

实现这个任务的方法是将函数名保留为字典值,并且在使用键调用时,添加括号'()'。

# Python3 code to demonstrate the working of
# Functions as dictionary values
# Using Without params

# call Gfg fnc
def print_key1():
    return "This is Gfg's value"

# initializing dictionary
# check for function name as key
test_dict = {"Gfg": print_key1, "is": 5, "best": 9}

# printing original dictionary
print("The original dictionary is : " + str(test_dict))

# calling function using brackets
res = test_dict['Gfg']()

# printing result
print("The required call result : " + str(res))

案例 2:带参数

带参数调用的任务与上面的情况类似,在函数调用期间传递值就像通常的函数调用一样在括号内传递。

# Python3 code to demonstrate the working of
# Functions as dictionary values
# Using With params

# call Gfg fnc
def sum_key(a, b):
    return a + b

# initializing dictionary
# check for function name as key
test_dict = {"Gfg": sum_key, "is": 5, "best": 9}

# printing original dictionary
print("The original dictionary is : " + str(test_dict))

# calling function using brackets
# params inside brackets
res = test_dict['Gfg'](10, 34)

# printing result
print("The required call result : " + str(res))

原字典为:{'Gfg': , 'is': 5, 'best': 9} 要求的调用结果:44

来源:geeksforgeeks

© www.soinside.com 2019 - 2024. All rights reserved.