Home Backend Development Python Tutorial A brief introduction to lambda expressions in Python (with examples)

A brief introduction to lambda expressions in Python (with examples)

Oct 10, 2018 pm 03:34 PM
lambda expression

This article brings you a brief introduction to lambda expressions in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1: Definition of anonymous function

lambda parameter_list: expression

2: Ternary expression

The result returned when the condition is true if conditional judgment Else The result returned when the condition is false

3: map

map(func(arg1, arg2...), list1_arg1, list2_arg2), execute the previous one on the list input later. Function (mathematical mapping)

4: reduce

reduce(func(arg1, arg2...), list1_arg, init_value), continuous calculation, continuous call of lambda expression

五:filter

filter(func(arg1, arg2...), list1_arg1) When the conditions are met, the data will be filtered out!

6: Functional programming and imperative programming

def
    if --else
    for
    map reduce filter
    lambda
Copy after login

The idea of ​​functional programming. . . .
The idea of ​​imperative programming. . . .

Functional programming cares about the mapping of data, and imperative programming cares about the steps to solve problems

Functional programming:

(1) refers to functions and other The data types are the same and are on an equal footing. They can be assigned to other variables, can also be used as parameters, passed into another function, or used as the return value of other functions.

(2) Only use "expression" instead of "statement"

from functools import reduce
# ----------------------------------------------------------------#
#   匿名函数的定义
# ----------------------------------------------------------------#


def add(x, y):
    """
    add x and y
    :param x: x can be str or num
    :param y: y can be str or num
    :return:  x+y
    """
    return x + y


# lambda parameter_list: expression
user_sum = lambda arg1, arg2: arg1 + arg2

my_sum = user_sum(2, 2)
print(my_sum)

# ----------------------------------------------------------------#
#   三元表达式
# ----------------------------------------------------------------#
a, b = 1, 2
r = a if a > b else b
print(r)

# ----------------------------------------------------------------#
#   map(func, list),对后面输入的list分别执行前面的函数(数学的映射)
# ----------------------------------------------------------------#

myListMap1 = [1, 2, 3, 4]
myNewListMap1 = map(lambda x: x ** 2, myListMap1)  # 返回为map类型的数据结构
print(type(myNewListMap1))
print('myNewListMap1:', list(myNewListMap1))    # 转换为list


# 两个或者多个参数的map函数的使用
# 当两个参数种元素的个数不相同的时候会截断
myListMap2 = [1, 2, 3, 4]
myNewListMap2 = map(lambda x, y: x + y, myListMap1, myListMap2)
print('myNewListMap2:', list(myNewListMap2))


# ----------------------------------------------------------------#
#   reduce(func, list)连续计算,连续调用lambda表达式
# ----------------------------------------------------------------#

myListReduce = [1, 2, 3, 4]
# 把list中的值一个一个放进lambda中
r = reduce(lambda x, y: x + y, myListReduce)
print(r)

# 对第一个函数参数进行初始化
r = reduce(lambda x, y: x + y, myListReduce, 10)
print(r)

# filter
myListFilter = [3, 5, 6, 7, 8, 9, 10]
myNewListFilter = filter(lambda x: x % 2 == 1, myListFilter)
print('myNewListFilter:', list(myNewListFilter))

list_x = [1, 1, 0, 0]
filter_list = filter(lambda x: True if x == 1 else False, list_x)
print(list(filter_list))
Copy after login

The above is the detailed content of A brief introduction to lambda expressions in Python (with examples). 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)

Master functional programming and Lambda expressions in Go language Master functional programming and Lambda expressions in Go language Nov 30, 2023 am 10:46 AM

In the contemporary programming world, Functional Programming (FP for short) has gradually become a popular programming paradigm. It emphasizes using functions as basic building blocks to build programs, and regards the calculation process as the continuous transfer and conversion between functions. In recent years, Go language (also known as Golang) has gradually been widely used in various fields due to its simplicity, efficiency, concurrency safety and other characteristics. Although the Go language itself is not a purely functional programming language, it provides sufficient functionality.

How to do functional programming with PHP How to do functional programming with PHP Jun 06, 2023 am 08:21 AM

PHP is a widely used server-side language. One of the reasons why many web developers like to use PHP is its rich function library and simple and easy-to-use function syntax. Functional programming is a programming paradigm that well encapsulates data and behavior, making the code more modular and easy to maintain and test. In this article, we will introduce how to use PHP for functional programming. Functional Programming Basics The core idea of ​​functional programming is to treat functions as first-class citizens. Functions themselves can be passed, returned, and composed like variables.

Concurrent programming methods using Lambda expressions Concurrent programming methods using Lambda expressions Aug 20, 2023 am 08:17 AM

An important addition to JavaSE8 is the lambda expression feature. Use expressions to express method interfaces clearly and concisely. Collection libraries are very helpful. Collections can be iterated, filtered, and data extracted for useful purposes. To implement functional interfaces, lambda expressions are widely used. It saves a lot of code. Lambda expressions allow us to provide implementations without redefining methods. It is only here that the implementation code is formed by writing the code. The compiler does not create a .class file because Javalambda expressions are treated as functions. Functional interface @FunctionalInterface is a Java annotation that declares an interface as a functional interface.

Local variable type inference in Java 10: How to use var keyword in lambda expression Local variable type inference in Java 10: How to use var keyword in lambda expression Aug 02, 2023 pm 04:25 PM

Local variable type inference in Java10: How to use the var keyword in lambda expressions Introduction: Java10 introduces a new feature of local variable type inference, which allows us to use the var keyword to infer the type of a local variable when declaring it. While this feature may not be necessary in most cases, in some cases it can improve code readability and simplicity. This article will focus on how to use the var keyword in lambda expressions to implement local variable type inference.

Tips on using Lambda expressions in Java Tips on using Lambda expressions in Java Jun 16, 2023 am 09:07 AM

In Java 8, Lambda expressions are a very powerful tool that can greatly simplify code, making it more compact and easier to read. Lambda expressions can also improve the reusability and maintainability of code, thus effectively promoting development efficiency. This article will introduce some tips for using Lambda expressions in Java to help developers make better use of this powerful tool. Tip 1: Use Lambda expressions instead of anonymous inner classes before Java8 if we need

How to use LINQ and Lambda expressions in C# to improve code efficiency and solutions How to use LINQ and Lambda expressions in C# to improve code efficiency and solutions Oct 08, 2023 pm 03:37 PM

How to use LINQ and Lambda expressions in C# to improve code efficiency and solutions Introduction: With the continuous progress and development of software development, code efficiency has gradually become one of the important aspects that developers pay attention to. As a powerful programming language, C# provides many tools and features to improve the efficiency of your code. Among them, LINQ and Lambda expressions are two very useful features that can help developers write efficient code quickly and concisely. This article will introduce how to use LINQ and Lambda tables in C#

Why can't Python's lambda expressions contain statements? Why can't Python's lambda expressions contain statements? Aug 19, 2023 am 08:14 AM

Yes, Python Lambda expressions cannot contain statements. Before we delve into the reasons, let’s understand what Lambda is, its expressions and statements. Lambda expressions allow the definition of anonymous functions. A Lambda function is an anonymous function without a name. Let’s look at the syntax − lambdaarguments:expressions keyword lambda defines a lambda function. A lambda expression contains one or more parameters, but it can only have one expression. Lambda Example Let’s look at an example −myStr="Thisisit!"(lambdamyStr:pr

How to use Lambda functions in Java for functional programming How to use Lambda functions in Java for functional programming Jun 26, 2023 pm 04:04 PM

Functional programming is a very popular programming paradigm that emphasizes the use and composition of functions instead of statements and instructions in traditional imperative programming. Lambda functions added in Java 8 make functional programming in Java easier. In this article, we will cover the basics of Lambda functions and how to use it for functional programming. Definition of Lambda function A Lambda function is an undeclared method that can receive parameters and return values ​​and can be passed like an object.

See all articles