lambda expression
又被称为statement
,功能是:用来构造function
形式
lambda x, y:x + y
lambda
是关键字,x, y
是生成的函数的参数,可以没有参数,右边的x + y
是函数的返回值
示例
data = [x for x in range(10)]
t = list(filter(lambda x:x%2==0, data))
print(t)
-----result-----
[0, 2, 4, 6, 8]
解释一下filter
的功能:
filter(func, datalist)
接收两个参数,第一个参数是一个函数func
,filter
将会对第二个参数里面的每一个元素调用func
,调用结果为真的元素将一起被返回
说到lambda
就免不了说filter, map & reduce
这三个函数,因为这三个函数都是接收一个函数作参数
map(func, datalist)
将func
应用于datalist
的全部元素并返回处理之后的元素
示例
datalist = [1, 2, 3, 4]
list_new = list(map(lambda x:x**2, datalist))
print(list_new)
----
[1, 4, 9, 16]
reduce(func, datalist)
对datalist
里的元素进行成对的操作,第一次操作的结果和第三个元素一起传入func
依次类推
示例
from functools import reduce
datalist = [1, 2, 3, 4]
data = reduce(lambda x, y:x*y , datalist)
print(data)
-----
24
使用reduce
需要import,据说是Guido van Rossum讨厌lambda哈哈
下面回到lambda
以下内容基于这篇文章, 个人觉得写得挺透彻的
注意事项
lambda x:x**2
:
右边一定要是一个可以赋值给变量的expression,即使这个expression的值是None
例如:
lambda x:x*2
lambda x:x+3
lambda x:print(x)
上面的示例都是可以的,其中print返回的是None
为什么用lambda
其实lambda也不一定非用不可,比如上面map的功能就可以这样实现
data = [x**2 for x in datalist]
但是有时候用lambda却是非常方便的,例如下面这个我在文章里看到的例子
def __init__(self, parent):
"""Constructor"""
frame = tk.Frame(parent)
frame.pack()
btn22 = tk.Button(frame,
text="22", command=lambda: self.printNum(22))
btn22.pack(side=tk.LEFT)
btn44 = tk.Button(frame,
text="44", command=lambda: self.printNum(44))
btn44.pack(side=tk.LEFT)
对比一下没有用lambda的
def __init__(self, parent):
"""Constructor"""
frame = tk.Frame(parent)
frame.pack()
btn22 = tk.Button(frame,
text="22", command=self.buttonCmd22)
btn22.pack(side=tk.LEFT)
btn44 = tk.Button(frame,
text="44", command=self.buttonCmd44)
btn44.pack(side=tk.LEFT)
def buttonCmd22(self):
self.printNum(22)
def buttonCmd44(self):
self.printNum(44)
原文:
The thing to remember here is that a tk.Button expects a function object as an argument to the command parameter. That function object will be the function that the button calls when it (the button) is clicked. Basically, that function specifies what the GUI will do when the button is clicked.
So we must pass a function object in to a button via the *command *parameter. And note that — since different buttons do different things — we need a different function object for each button object. Each function will be used only once, by the particular button to which it is being supplied.