简体   繁体   English

在Python 2.7中的lambda函数内部使用print函数时出错

[英]Error using the print function inside a lambda function in Python 2.7

I'm running a simple code in Python 2.7, but it is giving me syntax error. 我正在Python 2.7中运行一个简单的代码,但这给了我语法错误。

hello = lambda first: print("Hello", first)

The error reported is SyntaxError: invalid syntax . 报告的错误是SyntaxError: invalid syntax

Python disallows the use of statements in lambda expressions : Python禁止在lambda表达式中使用语句:

Note that functions created with lambda expressions cannot contain statements or annotations. 请注意,使用lambda表达式创建的函数不能包含语句或注释。

print is a statement in Python 2, unless you import the print_function feature from __future__ : print是Python 2中的一条语句,除非您从__future__导入print_function功能:

>>> lambda x: print(x)
  File "<stdin>", line 1
    lambda x: print(x)
                  ^
SyntaxError: invalid syntax
>>> from __future__ import print_function
>>> lambda x: print(x)
<function <lambda> at 0x7f2ed301d668>

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

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