2017-03-31 125 views
2

我试图创建一个lambda函数,将全面传递到它的值,以小数位的数量也指定舍入lambda函数

我做了如下

c = lambda x: round(x, dp) 

其中DP是已经指定

然而,试图调用这给了以下错误

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "<stdin>", line 1, in <lambda> 
TypeError: 'int' object is not callable 

当我输入

c(23.2323332345435) 

我可能是半睡眠状态,但我敢肯定这是如何创建一个简单的lambda函数,我不明白为什么它不会工作。

我试着在括号包围无济于事

+2

我很确定你使用/ overrode'round',这是表达式中除了lambda以外唯一可调用的。使用'print(type(round))'来查明。 –

+2

为什么你首先使用'lambda',而不是只写'def c(x):...'? – chepner

+0

此外,函数将在* *调用时使用全局'dp'的值,而不是函数被定义*时的'dp'值。 – chepner

回答

1

好像你的阴影round

>>> c = lambda x: round(x) 
>>> c(13.4) 
13 
>>> round = 5 
>>> c = lambda x: round(x) 
>>> c(13.4) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 1, in <lambda> 
TypeError: 'int' object is not callable 

请检查您的代码,找到您指定对象名称的任何地方round。一旦找到它,请用另一个名称替换它。你可以阅读更多关于阴影here

2

那是,如果你不小心覆盖round,发生什么事之前或定义拉姆达后:

>>> c = lambda x: round(x, 5) 
>>> c(34.44) 
34.44 
>>> round=12 
>>> c(34.44) 
Traceback (most recent call last): 
    File "<string>", line 301, in runcode 
    File "<interactive input>", line 1, in <module> 
    File "<interactive input>", line 1, in <lambda> 
TypeError: 'int' object is not callable 
>>> 
2

你必须定义拉姆达功能之前定义DP的价值。 然后只有它的作品。

dp=5 
    c=lambda x,dp: round(x,dp) 
    print c(56.3453453453432) 

Here is the screenshot.

如果你想定义拉姆达功能后定义DP的值,那么你可以传递两个值的拉姆达功能。

c=lambda x,dp: round(x,dp) 
    dp=5 
    print c(56.3453453453432,dp)