[英]Python: Lambda Inside Print Function
There are many questions related to lambda and printing, but I could not find anything about this exact question. 关于lambda和打印有很多问题,但是我找不到关于此确切问题的任何信息。
I'd like to print the results of my lambda function within a print statement. 我想在打印语句中打印我的lambda函数的结果。 However, I am getting the wrong output.
但是,我得到了错误的输出。 I am using Python 3
我正在使用Python 3
from __future__ import print_function
file_name = "tester"
target = "blue"
prediction = "red"
print(file_name,target,prediction, str(lambda x: print('+') if target==prediction else print('-')))
This returns: 返回:
tester blue red <function <lambda> at 0x10918c2f0>
How do I get the actual results of the lambda function? 如何获得lambda函数的实际结果?
lambda
s are actually functions only. lambda
实际上仅是函数。 So, unless you invoke them you will not get any result from them. 因此,除非您调用它们,否则它们不会得到任何结果。 When you do
当你做
str(lambda x: print('+') if target==prediction else print('-'))
you are not actually invoking the lambda
function, but trying to get the string representation of the function itself. 您实际上并不是在调用
lambda
函数,而是试图获取该函数本身的字符串表示形式。 As you can see, the string representation has the information about what the object is and where it is stored in memory. 如您所见,字符串表示形式包含有关对象是什么以及它在内存中的存储位置的信息。
<function <lambda> at 0x10918c2f0>
Apart from that, the other problem in your lambda
is, you are actually invoking print
function in it. 除此之外,
lambda
的另一个问题是,您实际上正在调用其中的print
功能。 It will actually print the result but return None
. 它将实际打印结果,但返回
None
。 So, even if you invoke the lambda expression, you will get None
printed. 因此,即使调用lambda表达式,也将显示
None
。 For example, 例如,
>>> print(print("1"))
1
None
But, the good news is, in your case, you don't need lamda
at all. 但是,好消息是,就您而言,您根本不需要
lamda
。
print(file_name, target, prediction, '+' if target == prediction else '-')
The expression, 表达方式,
'+' if target == prediction else '-'
is called conditional expression and will make sure that you will get +
if target
is equal to prediction
, -
otherwise. 被称为条件表达式 ,并会确保你会得到
+
,如果target
是等于prediction
, -
不然。
>>> file_name, target, prediction = "tester", "blue", "red"
>>> print(file_name, target, prediction, '+' if target == prediction else '-')
tester blue red -
Note: If you are using Python 3.x, you don't need to import print_function
from the __future__
. 注:如果您使用Python 3.x中,你不需要导入
print_function
从__future__
。 It already is a function, in Python 3.x. 在Python 3.x中,它已经是一个函数。
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type(print)
<class 'builtin_function_or_method'>
只是打电话给lambda
print(file_name,target,prediction, (lambda: '+' if target==prediction else '-')())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.