【问题标题】:Python dict / OrderedDict: Assign function to value without executing it immediatelyPython dict / OrderedDict:将函数分配给值而不立即执行
【发布时间】:2017-09-05 11:56:22
【问题描述】:

我有一个 OrderedDict,我想将其值作为函数,但遇到了意外行为。初始化:

from collections import OrderedDict

options_dict=OrderedDict(["A",call_func_A(arg1,arg2)],
                         ["B",call_func_B(arg1,arg3)],
                         ["C",call_func_C(arg1,arg4)]

# Select options
options=["A","C"]

# Execute
result={}
for opt in options:
    result[opt]=options_dict[opt]

# Return result (or whatever)
print result

函数 call_func_A、call_func_B 和 call_func_C 在声明 options_dict 时被执行,而不是在随后的 for 循环中执行。

我希望函数调用等到 for 循环。

发生了什么事?

【问题讨论】:

  • call_func_A是函数,call_func_A(arg1,arg2)是调用函数

标签: python dictionary ordereddictionary


【解决方案1】:

在创建字典之前调用函数。您拨打了电话。

但是,您可以通过将函数嵌套在稍后调用的另一个函数中来延迟函数调用:

options_dict = OrderedDict([("A", lambda: call_func_A(arg1,arg2)),
                            ("B", lambda: call_func_B(arg1,arg3)),
                            ("C", lambda: call_func_C(arg1,arg4))])

# Select options
options = ["A", "C"]

# Execute
result = {}
for opt in options:
    result[opt] = options_dict[opt]() # <- call

使用functools.partial 可以达到相同的效果,但要执行额外的import 语句。

另一方面,由于您的函数参数可能是不变,因此我认为何时进行调用并不重要。您不妨保留在创建字典时调用函数的初始方法。

【讨论】:

  • 推迟的原因是相对昂贵我只想调用一个子集(按顺序)。也许有更简单的方法。
  • 目前我得到 TypeError: expected at most 1 arguments, got 3
  • @jtlz2 Moses Koledoye 提供的代码是正确的。问题在于如何创建 OrderedDict。查看我的答案的第一部分以了解正确的方法。
  • @jtlz2 这来自于你如何定义你的OrderedDict。我的回答中已经解决了这个问题。
【解决方案2】:

首先,您错误地声明了 OrderedDict。构造函数需要一个元组列表。相反,你给它多个列表。这样做:

options_dict=OrderedDict([("A",call_func_A(arg1, arg2)),
                          ("B",call_func_B(arg1, arg3)),
                          ("C",call_func_C(arg1, arg4))])

其次,当您声明options_dict 时,您不会将函数作为字典的值传递,而是将它们的结果传递:

options_dict=OrderedDict(["A",call_func_A(arg1,arg2)],
                         ["B",call_func_B(arg1,arg3)],
                         ["C",call_func_C(arg1,arg4)])

您通过call_func_A(arg1, arg2) 来呼叫他们。避免这种情况的一种相对简单的方法是省略 args:

options_dict=OrderedDict([("A",call_func_A),
                         ("B",call_func_B),
                         ("C",call_func_C)])

您可以将 args 存储在第二个 OrderedDict 中:

args_dict=OrderedDict([("A",[arg1, arg2]),
                      ("B",[arg3, arg4]),
                      ("C",[arg5, arg6])])

然后打电话给他们:

result={}
for opt in options:
    result[opt]=options_dict[opt](*args_dict[opt])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多