python - 将多个函数映射到键的字典 - Python

标签 python dictionary functional-programming

我知道我们可以使用像这样的函数的字典映射:

def call_functions(input)
    def function1():
        print "called function 1"

    def function2():
        print "called function 2"

    def function3():
        print "called function 3"

    tokenDict = {"cat":function1, 
                 "dog":function2, 
                 "bear":function3}

    return tokenDict[input]()

但是如果我们想将两个函数设置为字典中的一个值怎么办?喜欢:

tokenDict = {"cat":function1, function2
             "dog":function2
             ....

我尝试使用像 "cat":[function1, function2] 这样的列表,但是有更简单的方法吗?

当我调用它时,我希望它执行 function1 然后执行 function2

最佳答案

根据 Tyler 的评论,始终使用列表以保持一致性。然后使用列表理解输出应用列表中每个函数的结果。 这是一个工作示例:

def call_functions(i, val=3):

    def function1(x):
        return x*1

    def function2(x):
        return x*2

    def function3(x):
        return x*3

    tokenDict = {"cat": [function1, function2],
                 "dog": [function2], 
                 "bear": [function3]}

    return [f(val) for f in tokenDict[i]]

call_functions('cat')   # [3, 6]
call_functions('dog')   # [6]
call_functions('bear')  # [9]

旁注:你不应该隐藏内置的input

关于python - 将多个函数映射到键的字典 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51484809/

相关文章:

python - OpenCV 将帧写入文件 python

python - 定义类 : Module takes at most 2 arguments

python - 在 python 中导入模块时会发生什么

python - 使用 PyCharm,为什么运行 Django 项目时的 PYTHONPATH 与运行 manage.pysyncdb 任务时不同?

scala - 在scala中使用map和reduce进行矢量积

python - 用递归函数替换简单的 for 循环?

python - 通过Python将csv文件转换为numpy数组

python - 将文本文件转换为Python字典

kotlin - 什么功能方法可以帮助我实现速度返回算法?

java - 将嵌套 for 循环转换为维护数据的流