在 Python 2.7 中的 lambda 函数中使用打印函数时出错 [英] Error using the print function inside a lambda function in Python 2.7

查看:80
本文介绍了在 Python 2.7 中的 lambda 函数中使用打印函数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 2.7 中运行一个简单的代码,但它给了我语法错误.

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

报告的错误是SyntaxError: invalid syntax.

解决方案

Python 不允许在 lambda 表达式:

<块引用>

请注意,使用 lambda 表达式创建的函数不能包含声明或注释.

print 是 Python 2 中的语句,除非您从 __future__:

<预><代码>>>>拉姆达 x:打印(x)文件<stdin>",第 1 行拉姆达 x:打印(x)^语法错误:无效语法>>>从 __future__ 导入 print_function>>>拉姆达 x:打印(x)<函数<lambda>在 0x7f2ed301d668>

I'm running a simple code in Python 2.7, but it is giving me syntax error.

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

The error reported is SyntaxError: invalid syntax.

解决方案

Python disallows the use of statements in lambda expressions:

Note that functions created with lambda expressions cannot contain statements or annotations.

print is a statement in Python 2, unless you import the print_function feature from __future__:

>>> 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>

这篇关于在 Python 2.7 中的 lambda 函数中使用打印函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆