【发布时间】: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