Table of Contents
Lambda function introduction
Why use Lambda function?
What is a higher-order function?
Python built-in higher-order functions
Map function
Filter function
Reduce function
高阶函数的替代方法
列表推导式
字典推导式
一个简单应用
如何快速找到多个字典的公共键
写在最后
Home Backend Development Python Tutorial Lambda function, the king of all in Python

Lambda function, the king of all in Python

Apr 14, 2023 pm 11:22 PM
python lambda

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles