我在试着找出Python的lambda。lambda是那些在现实生活中应该被遗忘的“有趣”语言项之一吗?
我确信有一些边缘情况可能需要它,但是考虑到它的模糊性,它在未来版本中被重新定义的可能性(我基于它的各种定义的假设)以及降低的编码清晰度——应该避免它吗?
这让我想起了C类型的溢出(缓冲区溢出)——指向顶部变量并重载以设置其他字段值。这感觉有点像技术人员的表演,但维护程序员的噩梦。
我在试着找出Python的lambda。lambda是那些在现实生活中应该被遗忘的“有趣”语言项之一吗?
我确信有一些边缘情况可能需要它,但是考虑到它的模糊性,它在未来版本中被重新定义的可能性(我基于它的各种定义的假设)以及降低的编码清晰度——应该避免它吗?
这让我想起了C类型的溢出(缓冲区溢出)——指向顶部变量并重载以设置其他字段值。这感觉有点像技术人员的表演,但维护程序员的噩梦。
当前回答
使用lambdas的一个有用的例子是提高长列表推导式的可读性。 在这个例子中,loop_dic是为了清晰起见的缩写,但是假设loop_dic非常长。如果你只是使用一个包含i的普通值,而不是该值的lambda版本,你会得到一个NameError。
>>> lis = [{"name": "Peter"}, {"name": "Josef"}]
>>> loop_dic = lambda i: {"name": i["name"] + " Wallace" }
>>> new_lis = [loop_dic(i) for i in lis]
>>> new_lis
[{'name': 'Peter Wallace'}, {'name': 'Josef Wallace'}]
而不是
>>> lis = [{"name": "Peter"}, {"name": "Josef"}]
>>> new_lis = [{"name": i["name"] + " Wallace"} for i in lis]
>>> new_lis
[{'name': 'Peter Wallace'}, {'name': 'Josef Wallace'}]
其他回答
在我看来,lambda的一个好处是,它可以将简单表单的计算推迟到需要值时才进行。让我解释一下。
许多库例程的实现使得它们允许某些参数被调用(lambda是其中之一)。其思想是,实际值只在将要使用它的时候计算(而不是在调用它的时候)。一个(虚构的)例子可能有助于说明这一点。假设你有一个程序,它将记录一个给定的时间戳。您希望例程使用当前时间减去30分钟。你会这么说的
log_timestamp(datetime.datetime.now() - datetime.timedelta(minutes = 30))
现在假设实际函数只在某个事件发生时才被调用,并且您希望仅在该事件发生时计算时间戳。你可以这样做
log_timestamp(lambda : datetime.datetime.now() - datetime.timedelta(minutes = 30))
假设log_timestamp可以像这样处理可调用对象,它将在需要时计算这个值,届时您将获得时间戳。
当然,还有其他方法可以做到这一点(例如使用operator模块),但我希望我已经传达了这一点。
更新:这里有一个更具体的现实世界的例子。
更新2:我认为这是所谓的“坦克”的一个例子。
你说的是lambda表达式吗?就像
lambda x: x**2 + 2*x - 5
这些东西其实很有用。Python支持一种称为函数式编程的编程风格,在这种编程风格中,您可以将函数传递给其他函数来执行某些操作。例子:
mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
将mult3设置为[3,6,9],即原始列表中3的倍数的元素。这句话更短(有人可能会说,更清楚)
def filterfunc(x):
return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])
当然,在这个特殊的情况下,你可以做同样的事情作为一个列表推导:
mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]
(甚至作为range(3,10,3)),但还有许多其他更复杂的用例,在这些用例中,您不能使用列表推导式,lambda函数可能是写出一些东西的最短方法。
Returning a function from another function >>> def transform(n): ... return lambda x: x + n ... >>> f = transform(3) >>> f(4) 7 This is often used to create function wrappers, such as Python's decorators. Combining elements of an iterable sequence with reduce() >>> reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9]) '1, 2, 3, 4, 5, 6, 7, 8, 9' Sorting by an alternate key >>> sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x)) [5, 4, 6, 3, 7, 2, 8, 1, 9]
我经常使用lambda函数。我花了一段时间来适应它们,但最终我明白了它们是语言中非常有价值的一部分。
我不能说python对lambda的具体实现,但一般来说lambda函数真的很方便。它们是函数式编程的核心技术(甚至是技术),在面向对象程序中也非常有用。对于某些类型的问题,它们是最好的解决方案,所以当然不应该忘记!
我建议你仔细阅读闭包和map函数(它链接到python文档,但它存在于几乎所有支持函数结构的语言中),看看它为什么有用。
我可以给你们一个我需要的例子。我正在制作一个图形程序,其中使用右键单击文件并为其分配三个选项之一。事实证明,在Tkinter(我在其中编写的GUI接口程序)中,当有人按下按钮时,它不能被分配给接受参数的命令。所以如果我选择了其中一个选项并希望我选择的结果是:
print 'hi there'
那没什么大不了的。但是如果我需要我的选择有一个特定的细节。例如,如果我选择选项A,它会调用一个函数,该函数接受依赖于选项A、B或C的一些参数,TKinter不支持这一点。拉姆达是唯一的选择,实际上…
I started reading David Mertz's book today 'Text Processing in Python.' While he has a fairly terse description of Lambda's the examples in the first chapter combined with the explanation in Appendix A made them jump off the page for me (finally) and all of a sudden I understood their value. That is not to say his explanation will work for you and I am still at the discovery stage so I will not attempt to add to these responses other than the following: I am new to Python I am new to OOP Lambdas were a struggle for me Now that I read Mertz, I think I get them and I see them as very useful as I think they allow a cleaner approach to programming.
He reproduces the Zen of Python, one line of which is Simple is better than complex. As a non-OOP programmer reading code with lambdas (and until last week list comprehensions) I have thought-This is simple?. I finally realized today that actually these features make the code much more readable, and understandable than the alternative-which is invariably a loop of some sort. I also realized that like financial statements-Python was not designed for the novice user, rather it is designed for the user that wants to get educated. I can't believe how powerful this language is. When it dawned on me (finally) the purpose and value of lambdas I wanted to rip up about 30 programs and start over putting in lambdas where appropriate.