我发现python不喜欢用lambda方程进行操作。在lambda方程上运行
y = lambda x: exp(2*x)
m = lambda x: 2*y - x
产生了错误:
TypeError: unsupported operand type(s) for *: 'int' and 'function'
我目前工作很长的公式,我需要替换大量的公式,但是Python不会让我上拉姆达方程进行操作。 在python中有没有办法解决这个问题?
我发现python不喜欢用lambda方程进行操作。在lambda方程上运行
y = lambda x: exp(2*x)
m = lambda x: 2*y - x
产生了错误:
TypeError: unsupported operand type(s) for *: 'int' and 'function'
我目前工作很长的公式,我需要替换大量的公式,但是Python不会让我上拉姆达方程进行操作。 在python中有没有办法解决这个问题?
使用lambda
创建匿名函数。因此,你需要把它叫为一个:
m = lambda x: 2*y(x) - x
# ^^^
请参见下面的演示:
>>> lamb = lambda x: x * 2
>>> lamb
<function <lambda> at 0x0227D108>
>>> lamb(4)
8
>>>
或者,简单来说,这样做:
y = lambda x: exp(2*x)
是一样的做这个:
def y(x):
return exp(2*x)
但是请注意即PEP 0008的官方风格指南Python代码,谴责命名lambda表达式和到位的正常功能,使用它们的做法:
Always use a
def
statement instead of an assignment statement that binds alambda
expression directly to an identifier.Yes:
def f(x): return 2*x
No:
f = lambda x: 2*x
The first form means that the name of the resulting function object is specifically
f
instead of the generic<lambda>
. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit alambda
expression can offer over an explicitdef
statement (i.e. that it can be embedded inside a larger expression)
来源:http://legacy.python.org/dev/peps/pep-0008/#programming-recommendations
我爱你...它的工作 – user3065619 2014-11-03 23:03:27
@ user3065619只是想通过*为什么*它的工作原理:你不能使用lambda在第二行包含表达式,你只能用它来包含* result *的表达。 – Marius 2014-11-03 23:04:58
为什么*姓名*匿名*功能?使用def语句 – JBernardo 2014-11-03 23:05:13
什么'这里exp'? ? – Hackaholic 2014-11-03 23:01:53
你期望得到的结果是什么?如果你在第二行“扩展”了“y”,它会是什么样子? – Marius 2014-11-03 23:02:20