为什么打印在 lambda 中不起作用? [英] Why doesn't print work in a lambda?
本文介绍了为什么打印在 lambda 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这不起作用?
lambda: print "x"
这不是一个单一的陈述,还是别的什么?关于 lambda 中允许的内容,文档似乎有点稀疏......
Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
推荐答案
lambda
的主体必须是单个表达式.在 Python 2.x 中,print
是一个语句.然而,在 Python 3 中,print
是一个 函数(函数应用程序是一个表达式,所以它可以在 lambda 中工作).如果您使用的是最新的 Python 2.x,您可以(并且应该,为了向前兼容:)使用向后移植的打印功能:
A lambda
's body has to be a single expression. In Python 2.x, print
is a statement. However, in Python 3, print
is a function (and a function application is an expression, so it will work in a lambda). You can (and should, for forward compatibility :) use the back-ported print function if you are using the latest Python 2.x:
In [1324]: from __future__ import print_function
In [1325]: f = lambda x: print(x)
In [1326]: f("HI")
HI
这篇关于为什么打印在 lambda 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文