【问题标题】:How to cancel the dictionary to initialize ? python3.3如何取消字典初始化? python3.3
【发布时间】:2012-12-14 01:43:23
【问题描述】:

先解释一下代码会更容易解释我的问题。

def initialize_function(num,instruction,emplacement1,emplacement2,current_pipeline):
    function_mapping={
    "LOAD" : LOAD(num,emplacement1,emplacement2,current_pipeline),
    "STORE" : STORE(num,emplacement1,emplacement2,current_pipeline),
    "MOVE" : MOVE_IADD(num,emplacement1,emplacement2,current_pipeline),
    "IADD" : MOVE_IADD(num,emplacement1,emplacement2,current_pipeline),
    "FADD" : FADD(num,emplacement1,emplacement2,current_pipeline)
    }
    current_pipeline=function_mapping[instruction] 
    return(current_pipeline)

initialize_function 函数有一个参数instructioninstruction 是一个字符串,等效于 function_mapping 字典的其中一个键。 因此,当我执行current_pipeline=function_mapping[instruction] 时,它应该只执行instruction 的值。但事实并非如此。实际上,function_mapping 字典在查找密钥 instruction 之前已初始化,因此它会依次执行所有函数 LOAD、STORE、MOVE、IADD、FADD。

我能做什么?

提前谢谢你:)

MFF

【问题讨论】:

    标签: python dictionary python-3.x


    【解决方案1】:

    由于所有函数的参数都相同,因此应该可以:

    def initialize_function(num,instruction,emplacement1,emplacement2,current_pipeline):
        function_mapping={
        "LOAD" : LOAD,
        "STORE" : STORE,
        "MOVE" : MOVE_IADD,
        "IADD" : MOVE_IADD,
        "FADD" : FADD
        }
        current_pipeline=function_mapping[instruction](num,emplacement1,emplacement2,current_pipeline)
        return(current_pipeline)
    

    说明:您的字典值将在运行时评估,因为您实际上是在调用函数。你想传递对它们的引用,因为函数是 python 中的第一类对象,你可以这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-17
      • 2020-09-15
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多