Let me introduce you to the anonymous function in Python today.
anonymous functions
lambda
defined by keywords
- Parameter list does not require parentheses
- The colon is not the opening of a new statement block.
- Can only be written on one line
- Without a return statement, the value of the last expression is the return value
A simple example:
In [1]: lambda x: x+1Out[1]: <function __main__.<lambda>># 第一种用法(lambda x: x + 1)(3) # 第一个括号用来改变优先级,第二对括号表示函数调用In [2]: (lambda x: x+1)(3)Out[2]: 4# 第二种用法,把匿名函数赋值给变量f = lambda x: x + 1f(5)In [3]: f = lambda x: x+1In [4]: f(5)Out[4]: 6lambda x, y: x + y# 也可以这样调用(lambda x, y: x + y)(3, 5) # 第一个括号是用来改变优先级的,第二个括号是调用函数的add = lambda x, y: x + yadd(3, 5)
You can also set default parameters:
lambda x, y=1: x + yadd = lambda x, y=1: x + yadd(3)# 调用的时候也可以用关键字参数add(x=5)lambda x, y=1: x + y<function <lambda> at 0x1019e10d0>add = lambda x, y=1: x + yadd(3)4# 调用的时候也可以用关键字参数add(x=5)6
Can I have variable parameters?
In [5]: f = lambda *x: xIn [6]: f(1, 2, 3)Out[6]: (1, 2, 3)In [7]: lst = [1, 2, 3]In [8]: f(*lst)Out[8]: (1, 2, 3)
Are the keyword parameters OK?
In [9]: f = lambda **kw: kwIn [10]: f(a=0)Out[10]: {‘a‘: 0}In [11]: dict01 = {‘name‘: ‘lavenliu.cn‘, ‘age‘: 23}In [12]: f(**dict01)Out[12]: {‘age‘: 23, ‘name‘: ‘lavenliu.cn‘}
Variable parameters are used in conjunction with variable keyword parameters?
In [13]: (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}In [14]: (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}
Can I have a parameter slot?
In [15]: f = lambda x, *, y: x+yIn [16]: f(1, y=3)Out[16]: 4
The parameter changes supported by the normal function are supported by the anonymous function.
One more example:
In [17]: concat = lambda *args: ‘‘.join(args)In [18]: concat(‘a‘, ‘b‘, ‘c‘)Out[18]: ‘abc‘In [19]: lower = (lambda x, y: x if x < y else y)In [20]: lower(7, 3)Out[20]: 3In [21]: lower(‘a‘, ‘b‘)Out[21]: ‘a‘In [22]: lower(2.3, 4.5)Out[22]: 2.3
Anonymous functions are usually used in conjunction with higher-order functions, passed in as arguments, or returned as return values.
Anonymous functions are best not defined as recursive functions.
In [29]: fib = lambda n: 1 if n == 0 or n == 1 else fib(n-1) + fib(n-2)In [30]: fib(5)Out[30]: 8
An example:
from collections import namedtupleUser = namedtuple(‘User‘, [‘name‘, ‘age‘])users = [User(‘lavenliu‘, 23), User(‘taoqi‘, 20)]def get_age(user): return user.agesorted(users, key=get_age)[User(name=‘taoqi‘, age=20), User(name=‘lavenliu‘, age=23)]# 或者使用匿名函数sorted(users, key=lambda x: x.age)[User(name=‘taoqi‘, age=20), User(name=‘lavenliu‘, age=23)]list(map(lambda x: x.age, users))list(filter(lambda x: x.age < 30, users))
Implement a map function yourself,
In [31]: def map_(fn, it): ...: return [fn(x) for x in it] ...: In [32]: def square(n): ...: return n ** 2 ...: In [33]: lst1 = [1, 2, 3, 4, 5]# 使用自定义的map函数In [34]: map_(square, lst1)Out[34]: [1, 4, 9, 16, 25]
Implement a filter function yourself,
def filter_(fn, it): return [x for x in it if fn(x)]
Today's content is here, you are welcome to continue to pay attention to the public number: small white Technology Inn.
anonymous function of Python