我目前在教自己python 3,还有一件事情让我感到困惑:我的意思是我期望的一切,包括lambda。但是,如何编写代码块?Python:如何编写一段代码?
比如我怎么用Python语言编写以下简单的程序代码(2或3):
( (lambda() (display "hello ") (display "world") (newline)) )
=> hello world
现在蟒蛇:
=> >>> lambda :print("hello") print("world");
我目前在教自己python 3,还有一件事情让我感到困惑:我的意思是我期望的一切,包括lambda。但是,如何编写代码块?Python:如何编写一段代码?
比如我怎么用Python语言编写以下简单的程序代码(2或3):
( (lambda() (display "hello ") (display "world") (newline)) )
=> hello world
现在蟒蛇:
=> >>> lambda :print("hello") print("world");
想你指的这个,
>>> f = lambda : print("hello","world")
>>> f
<function <lambda> at 0x7faeca581d08>
>>> f()
hello world
这不是你写Python的方式。 Lambda是句法糖非常简单功能只,并且只能包含一个单一的表达式。如果你想做其他任何事情,你必须写一个函数。
def hello_world():
print("hello")
print("world")
请注意,这不是lambda的事实没有任何区别;你仍然可以通过hello_world
作为第一类对象。
如果你真的想在一个lambda表达式中对多个表达式进行排序,可以通过构建多个子表达式中的数据结构来排序“伪造”。 Python会在构建数据结构时评估数据结构中的项目。元组是更高效的数据结构中的一种使用方法:
>>> f = lambda: (print('Hello ', end=''), print('World'))
>>> x = f()
Hello World
注意˚F返回包含两个打印函数调用的返回值的元组,每一个都是无。
>>> x
(None, None)
这工作,你期望它的工作,因为Python是保证从左至右评估,以便元组表达式,如这里所描述的方法:
很好的解释,但你的代码打印两行,当它应该是一个:'print('hello world')' –