我在 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/