gpt4 book ai didi

python - Lambda 用于不同的列表元素

转载 作者:行者123 更新时间:2023-11-28 21:37:19 24 4
gpt4 key购买 nike

我正在尝试使用 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].

最佳答案

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

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了解更多详情。

关于python - Lambda 用于不同的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com