Introduction to Python Programming (014) - Python's Lambda function (anonymous function)

Introduction to Python Programming (014) - Python's Lambda function (anonymous function)

1. Definition of anonymous function

Lambda functions are one of the core concepts in functional programming. Python provides an easy way to define lambda functions. Anonymous functions can implement efficient function functions in one line of code without defining a function. Anonymous functions can be used directly in expressions, which is very convenient. The syntax format of anonymous functions is as follows:

lambda [arguments] : expression

illustrate:

(1) arguments: formal parameter list, multiple formal parameters separated by commas, or without parameters.

The form of the formal parameter list is as follows:

a, b
a=1, b=2
*args
**kwargs
a, b=1, *args

(2) Expression: The expression of the function return value. There can only be one expression.

The expression is of the form:

6
a + b
sum(b)
6 if a >10 else 7

(3) The return value of lambda is the address of a function, which is the function object.

For example:

fadd = lambda x,y:x+y
print(fadd)
print(fadd(3,2))

运行结果如下:
===================== RESTART: C:\Python\Python38\First.py =====================
<function <lambda> at 0x00000266BFC99EE0>
5

2. Characteristics of anonymous functions

(1) Lambda function is anonymous

The so-called anonymous function, in layman's terms, is a function without a name.

(2) Lambda function has input and output

The input is the value passed into the parameter list [arguments], and the output is the value calculated based on the expression expression.

(3) Lambda function has its own namespace

You cannot access parameters outside your own parameter list or in the global namespace, and can only complete very simple functions.

Common Lambda function examples:

lambda x, y: x+y			# 函数的输入为x和y,输出是它们的和:x+y
lambda *args: sum(args)		 # 输入是任意个数参数,输出是它们的和
lambda **kwargs: 6			# 输入是任意键值对参数,输出是6

3. Common uses of anonymous functions

1. Call after naming

If we just need a simple function, lambda is a good choice and can be considered as an easier way to define a function. We can give it a name and use it like a normal function. The form of the call is as follows:

fun_name = lambda arguments : expression
fun_name(arguments)

For example:

fun_perimeter = lambda r:3.14 * r * 2
fun_area = lambda r:3.14 * r ** 2
print("圆的周长:",fun_perimeter(5))
print("圆的面积:",fun_area(5))

运行结果如下:
===================== RESTART: C:\Python\Python38\First.py =====================
圆的周长: 31.400000000000002
圆的面积: 78.5

2. Call directly

The syntax format for directly calling the lambda function is as follows:

(lambda arguments : expression)(arguments)

For example:

print("圆的周长:",(lambda r:3.14 * r * 2)(5))
print("圆的面积:",(lambda r:3.14 * r ** 2)(5))

运行结果如下:
===================== RESTART: C:\Python\Python38\First.py =====================
圆的周长: 31.400000000000002
圆的面积: 78.5

3. Pass the Lambda function as a parameter to other functions (usually given the key parameter)

(1) max() function

The max() function returns the maximum value of the given parameter, which can be a sequence. The syntax format of the max() function is as follows:

max( x, y, z, .... )

说明:返回给定参数的最大值

For example: the Lambda function determines which value of the tuple is sorted.

num = [(100, 2.5), (150, 0.2), (80, 3.4), (120, 1.8)]
y = max(num, key=lambda x: x[0])   # 按元组的第1个值排序取最大值
print(y)
y = max(num, key=lambda x: x[1])   # 按元组的第2个值排序取最大值
print(y)

运行结果如下:
===================== RESTART: C:\Python\Python38\First.py =====================
(150, 0.2)
(80, 3.4)

(2) sorted() function

The sorted() function sorts all iterable objects. The syntax format of the sorted() function is as follows:

sorted(iterable, key=None, reverse=False)
参数说明:
(1)iterable:可迭代对象。
(2)key:指定用来进行比较的元素,指定可迭代对象中的一个元素进行排序。
(3)reverse:排序规则,reverse = True 降序, reverse = False 升序(默认)。
(4)返回值:返回重新排序的列表。

The difference between sort and sorted:

(1) sort is a method applied to lists, and sorted can perform sorting operations on all iterable objects.

(2) The sort method of list operates on an existing list. The sorted function returns a new list, not an operation based on the original one.

Example 1: Operations on lists

num = [2,3,22,102,-87,11,-23]
print(sorted(num))  # 升序排列
print(sorted(num,key=lambda x :abs(x)))  # 按绝对值升序排列,参数x接收的是列表的元素
stu = ["Jerry","Mark","tom","Black","zhangping","Liugang","WANGLIN"]
print(sorted(stu))   # 对名字排序(区分大小写)
print(sorted(stu,key=str.lower))   # 对名字排序(转换为小写后排序,即:不区分大小写)
print(sorted(stu,key=lambda x:x.lower()))   # 作用同上
print(sorted(stu,key=lambda x:len(x)))      # 按字符串的长度排序
# 参数x接收的是列表的元素,参数x接收的是列表的元素,参数x接收的是列表的元素
lang = [(11,"java"),(101,"go"),(201,"c"),(17,"vb"),(21,"c++")]
print(sorted(lang,key=lambda x:x[0]))  # 按列表中的元组的第一列排序
print(sorted(lang,key=lambda x:x[1]))  # 按列表中的元组的第二列排序

运行结果如下:
===================== RESTART: C:\Python\Python38\First.py =====================
[-87, -23, 2, 3, 11, 22, 102]
[2, 3, 11, 22, -23, -87, 102]
['Black', 'Jerry', 'Liugang', 'Mark', 'WANGLIN', 'tom', 'zhangping']
['Black', 'Jerry', 'Liugang', 'Mark', 'tom', 'WANGLIN', 'zhangping']
['Black', 'Jerry', 'Liugang', 'Mark', 'tom', 'WANGLIN', 'zhangping']
['tom', 'Mark', 'Jerry', 'Black', 'Liugang', 'WANGLIN', 'zhangping']
[(11, 'java'), (17, 'vb'), (21, 'c++'), (101, 'go'), (201, 'c')]
[(201, 'c'), (21, 'c++'), (101, 'go'), (11, 'java'), (17, 'vb')]

Example 2: Operation on dictionary

lang = {
    
    11:"java",101:"go",201:"c",17:"vb",21:"c++"}
print(lang)
print(sorted(lang.items(),key=lambda x:x[0]))  # 按字典的 key 排序
print(sorted(lang.items(),key=lambda x:x[1]))  # 按字典的 value 排序

运行结果如下:
===================== RESTART: C:\Python\Python38\First.py =====================
{
    
    11: 'java', 101: 'go', 201: 'c', 17: 'vb', 21: 'c++'}
[(11, 'java'), (17, 'vb'), (21, 'c++'), (101, 'go'), (201, 'c')]
[(201, 'c'), (21, 'c++'), (101, 'go'), (11, 'java'), (17, 'vb')]

Guess you like

Origin blog.csdn.net/weixin_44377973/article/details/132174099