【问题标题】:Higher order function pseudo dictionary高阶函数伪字典
【发布时间】:2020-05-24 18:41:33
【问题描述】:

我正在尝试使用高阶函数实现一种键值对存储。 现在请您原谅,这可能是一段非常混乱且难以理解的代码,但这里是:

def empty_dic():
   return lambda x : False

def look_up(key,dic):
   return dic(key)

def add_elem(key,value,dic):
   return lambda x : value if x == key else dic(x)

def change_value(key,new_value,dic):
   return lambda x : new_value if key == x else dic(key)

mydic = change_value("colour","red",add_elem("brand","audemars",add_elem("colour","blue",empty_dic())))

print (look_up("brand",mydic))

结果:蓝色

在这种情况下,我希望look_up 函数返回“audemars”,但它却给了我最后一个“add_elem”函数的颜色。

【问题讨论】:

    标签: python dictionary higher-order-functions


    【解决方案1】:

    change_value函数中的错误,替换

    lambda x : new_value if key == x else dic(key)
    

    lambda x : new_value if key == x else dic(x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      相关资源
      最近更新 更多