Home > Backend Development > Python Tutorial > Lambda function, the king of all in Python

Lambda function, the king of all in Python

PHPz
Release: 2023-04-14 23:22:01
forward
1445 people have browsed it

Lambda function, the king of all in Python

Lambda function introduction

The Lambda function is also known as an anonymous (no name) function, which directly accepts the number of parameters and the condition or operation performed using the parameters, The parameters are separated by colons and the final result is returned. In order to perform a small task while writing code on a large code base, or to perform a small task in a function, lambda functions are used in the normal process.

lambda argument_list:expersion
Copy after login

argument_list is a parameter list, its structure is the same as the parameter list of a function in Python

a,b
a=1,b=2
*args
**kwargs
a,b=1,*args
空
....
Copy after login

expression is an expression about parameters, the parameters that appear in the expression It needs to be defined in argument_list, and the expression can only be a single line.

1
None
a+b
sum(a)
1 if a >10 else 0
[i for i in range(10)]
...
Copy after login

The difference between ordinary functions and Lambda functions

  • No name Lambda functions have no names, while ordinary operations have an appropriate name.
  • Lambda function has no return value. An ordinary function built using the def keyword returns a value or sequence data type, but a complete process is returned in a Lambda function. Suppose we want to check if a number is even or odd, using lambda function syntax similar to the code snippet below.
b = lambda x: "Even" if x%2==0 else "Odd"
b(9)
Copy after login
  • Functions are written and created in only one line. Lambda functions are written and created in only one line, while indentation is used in normal functions.
  • Not used for code reuse. Lambda functions cannot for code reuse, or this function cannot be imported in any other file. In contrast, normal functions are used for code reuse and can be used in external files.

Why use Lambda function?

Generally, we do not use Lambda function, but use it with higher-order functions. A higher order function is a function that requires more than one function to complete a task, or when a function returns any other function, a Lambda function can be optionally used.

What is a higher-order function?

Let’s understand higher-order functions through an example. Suppose you have a list of integers and three outputs must be returned.

  • The sum of all even numbers in a list
  • The sum of all odd numbers in a list
  • The sum of all numbers divisible by three

First assume that an ordinary function is used to handle this problem. In this case, three different variables are declared to store the individual tasks, and a for loop is used to process and return the resulting three variables. This method works normally.

Now use the Lambda function to solve this problem. Then you can use three different Lambda functions to check whether a number to be tested is even, odd, or divisible by three, and then add a number to the result. .

def return_sum(func, lst):
 result = 0
 for i in lst:
 #if val satisfies func
 if func(i):
 result = result + i
 return result
lst = [11,14,21,56,78,45,29,28]
x = lambda a: a%2 == 0
y = lambda a: a%2 != 0
z = lambda a: a%3 == 0
print(return_sum(x, lst))
print(return_sum(y, lst))
print(return_sum(z, lst))
Copy after login

Here a higher order function is created where the Lambda function is passed as a part to the normal function. In fact, this type of code can be found everywhere on the Internet. However, many people ignore this function when using Python, or only use it occasionally, but in fact these functions are really convenient and can save more lines of code. Next let's take a look at these higher-order functions.

Python built-in higher-order functions

Map function

map() will map the specified sequence according to the provided function.

The Map function is a function that accepts two parameters. The first parameter function calls the function function with each element in the parameter sequence, and the second parameter is any iterable sequence data type. Returns a new list containing the value returned by each function.

map(function, iterable, ...)
Copy after login

The Map function will define a certain type of operation in the iterator object. Suppose we want to square array elements, i.e. map the square of each element of one array to another array that produces the desired result.

arr = [2,4,6,8]
arr = list(map(lambda x: x*x, arr))
print(arr)
Copy after login

We can use the Map function in different ways. Suppose there is a list of dictionaries containing details like names, addresses, etc. and the goal is to generate a new list containing all the names.

students = [
 {"name": "John Doe",
"father name": "Robert Doe",
"Address": "123 Hall street"
},
 {
 "name": "Rahul Garg",
 "father name": "Kamal Garg",
 "Address": "3-Upper-Street corner"
 },
 {
 "name": "Angela Steven",
"father name": "Jabob steven",
"Address": "Unknown"
 }
]
print(list(map(lambda student: student['name'], students)))
>>> ['John Doe', 'Rahul Garg', 'Angela Steven']
Copy after login

The above operations usually occur in scenarios such as obtaining data from a database or network crawling.

Filter function

Filter function filters out data based on given specific conditions. That is, set the filter conditions in the function, iterate the elements, and retain the elements with a return value of True. The map function operates on each element, while the filter function only outputs elements that meet specific requirements.

Suppose there is a list of fruit names, and the task is to output only those names that contain the character "g".

fruits = ['mango', 'apple', 'orange', 'cherry', 'grapes']
print(list(filter(lambda fruit: 'g' in fruit, fruits)))
Copy after login

filter(function or None, iterable) --> filter object

Returns an iterator for those iterable items where the function or item is true. If the function is None, returns true.

Reduce function

This function is quite special. It is not a built-in function of Python and needs to be imported through from functools import reduce. Reduce returns a single output value from a sequence data structure by applying a given function to reduce elements.

reduce(function, sequence[, initial]) -> value
Copy after login

Apply a two-argument function cumulatively to the items of a sequence, from left to right, thereby reducing the sequence to a single value.

If initial exists, it is placed before the item in the sequence and serves as the default value when the sequence is empty.

假设有一个整数列表,并求得所有元素的总和。且使用reduce函数而不是使用for循环来处理此问题。

from functools import reduce
lst = [2,4,6,8,10]
print(reduce(lambda x, y: x+y, lst))
>>> 30
Copy after login

还可以使用 reduce 函数而不是for循环从列表中找到最大或最小的元素。

lst = [2,4,6,8]
# 找到最大元素
print(reduce(lambda x, y: x if x>y else y, lst))
# 找到最小元素
print(reduce(lambda x, y: x if x<y else y, lst))
Copy after login

高阶函数的替代方法

列表推导式

其实列表推导式只是一个for循环,用于添加新列表中的每一项,以从现有索引或一组元素创建一个新列表。之前使用map、filter和reduce完成的工作也可以使用列表推导式完成。然而,相比于使用Map和filter函数,很多人更喜欢使用列表推导式,也许是因为它更容易应用和记忆。

同样使用列表推导式将数组中每个元素进行平方运算,水果的例子也可以使用列表推导式来解决。

arr = [2,4,6,8]
arr = [i**2 for i in arr]
print(arr)
fruit_result = [fruit for fruit in fruits if 'g' in fruit]
print(fruit_result)
Copy after login

字典推导式

与列表推导式一样,使用字典推导式从现有的字典创建一个新字典。还可以从列表创建字典。

假设有一个整数列表,需要创建一个字典,其中键是列表中的每个元素,值是列表中的每个元素的平方。

lst = [2,4,6,8]
D1 = {item:item**2 for item in lst}
print(D1)
>>> {2: 4, 4: 16, 6: 36, 8: 64}
# 创建一个只包含奇数元素的字典
arr = [1,2,3,4,5,6,7,8]
D2 = {item: item**2 for item in arr if item %2 != 0}
print(D2)
>>> {1: 1, 3: 9, 5: 25, 7: 49}
Copy after login

一个简单应用

如何快速找到多个字典的公共键

方法一

dl = [d1, d2, d3] # d1, d2, d3为字典,目标找到所有字典的公共键
[k for k in dl[0] if all(map(lambda d: k in d, dl[1:]))]
Copy after login

dl = [{1:'life', 2: 'is'},
{1:'short', 3: 'i'},
 {1: 'use', 4: 'python'}]
[k for k in dl[0] if all(map(lambda d: k in d, dl[1:]))]
# 1
Copy after login

解析

# 列表表达式遍历dl中第一个字典中的键
[k for k in dl[0]]
# [1, 2]
# lambda 匿名函数判断字典中的键,即k值是否在其余字典中
list(map(lambda d: 1 in d, dl[1:]))
# [True, True]
list(map(lambda d: 2 in d, dl[1:]))
#[False, False]
# 列表表达式条件为上述结果([True, True])全为True,则输出对应的k值
#1
Copy after login

方法二

# 利用集合(set)的交集操作
from functools import reduce
# reduce(lambda a, b: a*b, range(1,11)) # 10!
reduce(lambda a, b: a & b, map(dict.keys, dl))
Copy after login

写在最后

目前已经学习了Lambda函数是什么,以及Lambda函数的一些使用方法。随后又一起学习了Python中的高阶函数,以及如何在高阶函数中使用lambda函数。

除此之外,还学习了高阶函数的替代方法:在列表推导式和字典推导式中执行之前操作。虽然这些方法看似简单,或者说你之前已经见到过这类方法,但你很可能很少使用它们。你可以尝试在其他更加复杂的函数中使用它们,以便使代码更加简洁。

The above is the detailed content of Lambda function, the king of all in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template