简体   繁体   English

lambda python 3的意外输出

[英]Unexpected output for lambda python 3

I am trying to use lambda for a usecase, but it seems not working. 我试图使用lambda作为用例,但它似乎无法正常工作。 The following is what I tried 以下是我的尝试

The below is what I used, in stackflow I came across many people getting output for this, but for me its None 以下是我使用的,在stackflow中我遇到很多人为此获得输出,但对我来说它是无

from __future__ import print_function
f = lambda x: print(x)
f()
f("Hello") ### now out put is shown expected is Hello output
f("Hello") is None ## I checked if its None and it is
>>> True 

在此输入图像描述 then I tried something else 然后我尝试了别的东西

l = lambda x : sys.stdout.write(x)
l('hello') # this time its showing output as 5 instead of printing hello
>>> 5

在此输入图像描述

I even tried something which is not using lambda, unfourtunately that too not working, and got None 我甚至尝试了一些不使用lambda的东西,不幸的是,它没有工作,并且没有使用

from functools import partial
spam = partial(print, 'Hello!')
spam()
spam() is None
>>> True

I got this from the last answer in this question assigning print function to variable 我从这个问题的最后一个答案中得到了这个, 将print函数赋给变量

Can anyone help me what I am missing and why I am not able to print the string? 任何人都可以帮助我,我错过了什么,为什么我不能打印字符串?

What's not expected? 有什么不期望的? that f('Hello') is None evaluate to True ? f('Hello') is None评估为True Well that's expected because it is None . 那是预期的,因为它是None

lambda x: print(x) has no 'return', only a side effect, and the side effect is to print stuff to the output. lambda x: print(x)没有'return',只有副作用,副作用是将东西打印到输出。 This is similar to a function 这类似于一个功能

def func(x): 
    print(x)

which has no return statement, hence, if you evaluate the function, it's output will be None . 它没有return语句,因此,如果你评估函数,它的输出将是None

l = lambda x : sys.stdout.write(x)
l('hello') # this time its showing output as 5 instead of printing hello
>>> 5

it's probably because the write is not flushed, you can force this by manually calling 这可能是因为写入没有刷新,你可以通过手动调用来强制执行

sys.stdout.flush()

As for why it's returns hello5 is because the Python shell prints out the return value of the previous statement, sys.stdout.write() returns the count of the written characters which in case of 'hello' is 5. thus they become concatenated into hello5 . 至于为什么它返回hello5是因为Python shell打印出前一个语句的返回值, sys.stdout.write()返回写入字符的计数,如果'hello'为5则因此它们连接成hello5 If you ran this in a normal Python file ie python filename.py it would never print the 5 and only hello . 如果你在一个普通的Python文件中运行它,即python filename.py ,它将永远不会打印5和只有hello

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM