【问题标题】:Lambda used with different list elementsLambda 与不同的列表元素一起使用
【发布时间】:2018-09-20 00:39:28
【问题描述】:

我正在尝试使用来自Replacements for switch statement in Python 的以下示例来实现一个功能:

def f(x):
    return {
        '+': (lambda x: x[1] + x[2]),
        '-': (lambda x: x[1] - x[2])
    }[x[0]]

print(f(["+",2,3])) #Output should be 5. 

f(["-", 4, 1]) # Output should be 3.

我显然做错了什么。也许有人对此有更好的建议?

编辑

如果我想将 lambda 的输出保存在列表中然后返回呢?

例如:

def f(x, output):
    return {
        '+': (lambda x: x[1] + x[2]),
        '-': (lambda x: x[1] - x[2])
    }[x[0]]

output = [10, 20, 30, 40]

# to 2nd element in output list we add the last element in the list
print(f(["+",2,3], output)) #Output should be output = [10, 20, 33, 40]

output = [10, 20, 30, 40]
f(["-", 1, 100]) # Output should be [10, 120, 30, 40].

【问题讨论】:

    标签: python list lambda functional-programming


    【解决方案1】:

    记住将映射函数实际应用到变量:

    def f(x):
        return {
            '+': (lambda x: x[1] + x[2]),
            '-': (lambda x: x[1] - x[2])
        }[x[0]](x)
    
    print(f(["+",2,3]))  # 5 
    

    这是一个更灵活的版本:

    d = {'+': (lambda x: x[1] + x[2]),
         '-': (lambda x: x[1] - x[2])}
    
    def calculator(x, d):
        return d[x[0]](x)
    
    print(calculator(["+",2,3], d))  # 5
    

    一个更好的主意是使用您的调度程序只存储操作。

    更多详情请见@WillemVanOnsem's answer

    【讨论】:

      【解决方案2】:

      你的字典将一个字符串映射到一个函数,而不是那个函数的结果,这就是lambda的来源。你可以通过两种方式解决它:或者你直接计算结果,或者你在最后调用函数。

      def f(x):
          return {
              '+': (lambda: x[1] + x[2]),
              '-': (lambda: x[1] - x[2])
          }[x[0]]()  # calling the function!
      
      print(f(["+",2,3])) #Output should be 5. 
      
      f(["-", 4, 1]) # Output should be 3.

      不过,您也可以声明函数,并向其传递参数。这也将使其更加灵活,因为例如假设的f(["sin", 1.2]) 只有一个参数。例如,我们可以构造一个字典,例如:

      from operator import add, sub
      from math import sin
      
      FUNC_DICT = {
          '+': add,
          '-': sub,
          'sin': sin
      }

      那么我们的f 看起来像:

      def f(x):
          return FUNC_DICT[x[0]](*x[1:])

      所以我们用列表中的其余元素调用函数。

      【讨论】:

        猜你喜欢
        • 2020-01-27
        • 1970-01-01
        • 2021-12-16
        • 2022-01-01
        • 1970-01-01
        • 2020-03-12
        • 1970-01-01
        • 2011-10-05
        • 1970-01-01
        相关资源
        最近更新 更多