我在试着找出Python的lambda。lambda是那些在现实生活中应该被遗忘的“有趣”语言项之一吗?
我确信有一些边缘情况可能需要它,但是考虑到它的模糊性,它在未来版本中被重新定义的可能性(我基于它的各种定义的假设)以及降低的编码清晰度——应该避免它吗?
这让我想起了C类型的溢出(缓冲区溢出)——指向顶部变量并重载以设置其他字段值。这感觉有点像技术人员的表演,但维护程序员的噩梦。
我在试着找出Python的lambda。lambda是那些在现实生活中应该被遗忘的“有趣”语言项之一吗?
我确信有一些边缘情况可能需要它,但是考虑到它的模糊性,它在未来版本中被重新定义的可能性(我基于它的各种定义的假设)以及降低的编码清晰度——应该避免它吗?
这让我想起了C类型的溢出(缓冲区溢出)——指向顶部变量并重载以设置其他字段值。这感觉有点像技术人员的表演,但维护程序员的噩梦。
当前回答
我经常使用它,主要是作为空对象或将参数部分绑定到函数。
下面是一些例子:
实现空对象模式:
{
DATA_PACKET: self.handle_data_packets
NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)
对于参数绑定:
假设我有以下API
def dump_hex(file, var)
# some code
pass
class X(object):
#...
def packet_received(data):
# some kind of preprocessing
self.callback(data)
#...
然后,当我不想快速转储接收到的数据到一个文件,我这样做:
dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()
其他回答
lambdas在GUI编程中非常有用。例如,假设您正在创建一组按钮,并且希望使用单个参数化回调,而不是每个按钮使用唯一的回调。Lambda让你轻松完成:
for value in ["one","two","three"]:
b = tk.Button(label=value, command=lambda arg=value: my_callback(arg))
b.pack()
(注意:虽然这个问题是专门问lambda的,但你也可以使用functools。以获得相同类型的结果)
另一种方法是为每个按钮创建单独的回调,这可能导致重复的代码。
只是函数的一种奇特说法。除了它的名字,它没有什么晦涩、吓人或神秘的地方。当你读到下面这行,在脑海中用函数替换lambda:
>>> f = lambda x: x + 1
>>> f(3)
4
它只是定义了一个关于x的函数。其他一些语言,比如R,显式地说:
> f = function(x) { x + 1 }
> f(3)
4
你看到了什么?这是编程中最自然的事情之一。
你说的是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函数。我花了一段时间来适应它们,但最终我明白了它们是语言中非常有价值的一部分。
函数这是一种非官僚化的创建函数的方法。
就是这样。例如,假设你有一个主要函数,需要对值平方。我们来看看传统的方法和的方法
传统的方法:
def main():
...
...
y = square(some_number)
...
return something
def square(x):
return x**2
方式:
def main():
...
square = lambda x: x**2
y = square(some_number)
return something
看到区别了吗?
Lambda函数非常适合用于列表,比如列表推导式或映射。事实上,列表理解是一种使用lambda来表达自己的“python”方式。例:
>>>a = [1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]
让我们看看每个语法元素的含义:
[]:“给我一个清单” X **2:“使用这个新诞生的函数” 对于a中的x: "into each element in a"
很方便吧?创建这样的函数。让我们用lambda重写它:
>>> square = lambda x: x**2
>>> [square(s) for x in a]
[1,4,9,16]
现在让我们使用map,这是同样的东西,但更语言中立。Maps有两个参数:
(i)一个功能
(ii)可迭代对象
给你一个列表,其中每个元素它是应用于可迭代对象的每个元素的函数。
使用map,我们会得到:
>>> a = [1,2,3,4]
>>> squared_list = map(lambda x: x**2, a)
如果你掌握了lambdas和映射,你将拥有以简洁的方式操作数据的强大能力。Lambda函数既不晦涩,也不影响代码的清晰性。不要把难的东西和新东西混为一谈。一旦你开始使用它们,你就会发现非常清楚。
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.