python - 在 Python 2.7 的 lambda 函数中使用 print 函数时出错

标签 python python-2.7

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

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

报告的错误是SyntaxError: invalid syntax

最佳答案

Python 不允许在 lambda expressions 中使用语句:

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

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>

关于python - 在 Python 2.7 的 lambda 函数中使用 print 函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630009/

相关文章:

python - 不止一个条件满足numpy select

python quart 渲染模板

Python - 用户输入以确定 while 循环中的条件

python - 终端表 asciitables 和编码

python - 获取 pandas 中分类变量的映射

python - 当 Gif 后面跟着输入语句时,脚本会崩溃

python - 删除空括号并获取值

android - 如何以编程方式获取当前 Android 窗口屏幕的所有组件和小部件 Id?

python - cgi python 脚本似乎没有从 html 表单接收上传的文件

sql - 两个用不同语言编写的程序可以连接到同一个 SQL 数据库吗?