定义
在定义普通函数的时候,如下:
def fn():
pass
而匿名函数就是没有名字的函数,用lambda这个关键字来定义,lambda后面接一个参数x,然后用冒号分隔,然后定义一个函数体,如下:
>>> lambda x: x + 1
<function <lambda> at 0x0000027FC94F7288>
冒号后面不换行,这是python和js、java的区别
我们可以通过括号括起来,然后把参数放在后面的括号里,如下:
>>> (lambda x: x + 1)(3)
4
在匿名函数里面,x+1是我们的最后一条语句,所以匿名函数会返回最后一条语句的值。
匿名函数的特点:
- 用lambda来定义
- 参数列表不需要用括号括起来
- 冒号不是用来开启新的语句块
- 最后一个表达式没有return语句,最后一个表达式的值即返回值
匿名函数的调用
可以将整个函数表达式赋值给一个变量f:
>>> f = lambda x: x + 1
>>> f
<function <lambda> at 0x0000027FC94F7288>
>>> f(5)
6
如上的整个过程,就很方便的调用了函数
限制
匿名函数(lambda表达式),只能写在一行上,因此也被称为单行函数。
如下为一些使用情况:
#直接用0调用
>>> f = lambda : 0
>>> f()
0
#多个参数
>>> (lambda x, y: x + y)(3, 5)
8
#默认参数
>>> (lambda x, y=3: x + y)(2)
5
#位置可变参数
>>> (lambda *args: args)(*range(3))
(0, 1, 2)
#关键字可变参数
>>> (lambda *args, **kwargs: print(args, kwargs))(*range(3), **{str(x):x for x in range(3)})
(0, 1, 2) {'0': 0, '1': 1, '2': 2}
#keyword-only参数
>>> (lambda *, x: x)(x=3)
3
普通函数支持的参数变化,匿名函数也都支持
匿名函数的应用
sorted
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
往sorted里面传一个可迭代对象,key默认是None,然后reverse代表是否反转。
假设有一个User对象,有name和age属性:
from collections import namedtuple
User = namedtuple('User',['name','age'])
users = [User('kidult', 18), User('punch', 16)]
这个时候我们希望通过年龄的大小来对users作排序,如果没有匿名函数,我们就需要先定义一个函数:
def get_age(user):
return user.age
#向sorted函数传入一个users对象,并传递key值,使其对age进行排序
>>> sorted(users,key=get_age)
[User(name='punch', age=16), User(name='kidult', age=18)]
#匿名函数版本
>>> sorted(users, key=lambda x: x.age)
[User(name='punch', age=16), User(name='kidult', age=18)]
map
>>> help(map)
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
对每个可迭代对象进行一个迭代
>>> map(lambda x: x.age,users)
<map object at 0x0000027FC98C1688>
>>> list(map(lambda x: x.age, users))
[18, 16]
filter
>>> help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
把每个可迭代对象传进来,如果函数返回True,就存在,返回False,就不存在。如下:
>>> list(filter(lambda x: x.age < 17, users))
[User(name='punch', age=16)]
如下是map和filter的原型:
def _map(fn, it):
return (fn(x) for x in it)
def _filter(fn, it):
return (x for x in it if fn(x))
小结
这几个方法还是很有用的,特别是过滤器。