Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Lambda与不同的列表元素一起使用_Python_List_Lambda_Functional Programming - Fatal编程技术网

Python Lambda与不同的列表元素一起使用

Python Lambda与不同的列表元素一起使用,python,list,lambda,functional-programming,Python,List,Lambda,Functional Programming,我试图通过以下示例实现一个函数: 我显然做错了什么。也许有人对此有更好的建议 编辑: 如果我想将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

我试图通过以下示例实现一个函数:

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

编辑

如果我想将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].
请记住将映射函数实际应用于变量:

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

更好的办法是使用调度器仅存储操作


有关更多详细信息,请参阅。

词典将字符串映射到函数,而不是该函数的结果,这就是
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
看起来像:

def f(x):
    return FUNC_DICT[x[0]](*x[1:])
因此,我们使用列表中的其余元素调用该函数

from operator import add, sub
from math import sin

FUNC_DICT = {
    '+': add,
    '-': sub,
    'sin': sin
}
def f(x):
    return FUNC_DICT[x[0]](*x[1:])