Home Backend Development Python Tutorial 深入解析Python中的lambda表达式的用法

深入解析Python中的lambda表达式的用法

Jun 10, 2016 pm 03:07 PM
lambda python

普通的数学运算用这个纯抽象的符号演算来定义,计算结果只能在脑子里存在。所以写了点代码,来验证文章中介绍的演算规则。

我们来验证文章里介绍的自然数及自然数运算规则。说到自然数,今天还百度了一下,据度娘说,1993年后国家规定0是属于自然数。先定义自然数及自然数的运算规则:

用lambda表达式定义自然数(邱齐数)

0 := λf.λx.x
1 := λf.λx.f x
2 := λf.λx.f (f x)
3 := λf.λx.f (f (f x))
...
Copy after login

上面定义直观的意思就是数字n, 是f(x)的n阶函数。1就是f(x), 2就是f(f(x))....,严格来说,这样表述并不准确。其实每个邱奇数都是一个二阶函数,它有两个变量f和x。用二元命名函数来表达就是:

0 -> num0(f,x)=x
1 -> num1(f, x)=f(x)
2 -> num2(f,x)=f(f(x))
3 -> num3(f,x)=f(f(f(x)))
...
Copy after login

其中参数f是一个函数。这一段有点绕,但是不能理解这个,对后面的lambda演算理解会比较困难。

首先用递归法,定义邱齐数(自然数)

0是自然数, 度娘说1993年后,国家规定0是属于自然数。

每个自然数,都有一个后续。

用代码表达就是:

NUM0=lambda f: lambda x:x
SUCC=lambda n: lambda f: lambda x: f(n(f)(x))
Copy after login

后面则是定义运算符,包括加法,乘法,减法和幂。维基文章里没有介绍除法,估摸着除法定义比较复杂,一时讲不清楚。那我们也不验证了。

################################################
#define number calculus rules
################################################
 
#define Church numeral inductively.
#0 := λf.λx.x
#1 := λf.λx.f x
#2 := λf.λx.f (f x)
#3 := λf.λx.f (f (f x))
#...
NUM0=lambda f: lambda x:x
SUCC=lambda n: lambda f: lambda x: f(n(f)(x))
 
#define Operator
PLUS=lambda m: lambda n: m(SUCC)(n)
MULT= lambda m: lambda n: m(PLUS(n))(NUM0)
#define predecessor to obtain the previous number.
PRED= lambda n: lambda f: lambda x: n(lambda g: lambda h: h(g(f)))(lambda u:x)(lambda u:u)
SUB=lambda m: lambda n: n(PRED)(m)
POW=lambda b: lambda e: e(b)
Copy after login

定义完了什么是自然数和自然数的运算子。那么自然数的运算,就可以用lambda演算的方式计算了。

问题是上面的定义都是抽象的符号演算,我们需要有一个编码器来把上面的抽象的Church numeral符号编码成可以人来阅读的形式,还需把人输入的数字解码成抽象符号。

################################################
#create encoder to input/output Church numeral
################################################
 
class LambdaEncoding:
  @staticmethod
  def encoding(exp,encoder):
    return encoder().encoding(exp)
  @staticmethod
  def decoding(s, decoder):
    return decoder().decoding(s)
   
class NumEncoder:
  def encoding(self,num):
    f=lambda x:x+1
    return str(num(f)(0))
  def decoding(self,s):
    n=int(s)
    num=NUM0
    for i in range(n):
      num=SUCC(num)
    return num
Copy after login

嗯,有了编码器,就可以方便的来验证了。

################################################
#calculus demo
################################################
print("demo number calculus.\n"
   "don't input large number,"
   "it will cause to exceed maximum recursion depth!\n")
 
n1=input('input a number: ')
n2=input('input anohter number: ')
#decode string to Church numeral
num1=LambdaEncoding.decoding(n1,NumEncoder)
num2=LambdaEncoding.decoding(n2,NumEncoder)
   
#add
result=PLUS(num1)(num2)
 
print('{0} + {1} = {2}'.format(
  n1,
  n2,
  LambdaEncoding.encoding(result, NumEncoder)))
 
#mult
result=MULT(num1)(num2)
print('{0} X {1} = {2}'.format(
  n1,
  n2,
  LambdaEncoding.encoding(result, NumEncoder)))
#sub
result=SUB(num1)(num2)
print('{0} - {1} = {2}'.format(
  n1,
  n2,
  LambdaEncoding.encoding(result, NumEncoder)))
 
#POW
result=POW(num1)(num2)
print('{0} ^ {1} = {2}'.format(
  n1,
  n2,
  LambdaEncoding.encoding(result, NumEncoder)))
Copy after login

测试结果如下:

>>> 
demo number calculus.
don't input large number,it will cause to exceed maximum recursion depth!
 
input a number: 4
input anohter number: 3
4 + 3 = 7
4 X 3 = 12
4 - 3 = 1
4 ^ 3 = 64
>>>
Copy after login

神奇吧。

lambda和def的区别
python lambda是在python中使用lambda来创建匿名函数,而用def创建的方法是有名称的,除了从表面上的方法名不一样外,python lambda还有哪些和def不一样呢?
1 python lambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而def则会把函数对象赋值给一个变量。
2 python lambda它只是一个表达式,而def则是一个语句。
下面是python lambda的格式,看起来好精简阿。

lambda x: print x
Copy after login

如果你在python 列表解析里用到python lambda,我感觉意义不是很大,因为python lambda它会创建一个函数对象,但马上又给丢弃了,因为你没有使用它的返回值,即那个函数对象。也正是由于lambda只是一个表达式,它可以直接作为python 列表或python 字典的成员,比如:

info = [lamba a: a**3, lambda b: b**3]
Copy after login

在这个地方没有办法用def语句直接代替。因为def是语句,不是表达式不能嵌套在里面,lambda表达式在“:”后只能有一个表达式。也就是说,在def中,用return可以返回的也可以放在lambda后面,不能用return返回的也不能定义在python lambda后面。因此,像if或for或print这种语句就不能用于lambda中,lambda一般只用来定义简单的函数。
下面举几个python lambda的例子吧
1单个参数的:

g = lambda x:x*2
print g(3)
Copy after login

结果是6
多个参数的:

m = lambda x,y,z: (x-y)*z
print m(3,1,2)
Copy after login

结果是4

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is distinctIdistinguish related? Is distinctIdistinguish related? Apr 03, 2025 pm 10:30 PM

Although distinct and distinct are related to distinction, they are used differently: distinct (adjective) describes the uniqueness of things themselves and is used to emphasize differences between things; distinct (verb) represents the distinction behavior or ability, and is used to describe the discrimination process. In programming, distinct is often used to represent the uniqueness of elements in a collection, such as deduplication operations; distinct is reflected in the design of algorithms or functions, such as distinguishing odd and even numbers. When optimizing, the distinct operation should select the appropriate algorithm and data structure, while the distinct operation should optimize the distinction between logical efficiency and pay attention to writing clear and readable code.

How to understand !x in C? How to understand !x in C? Apr 03, 2025 pm 02:33 PM

!x Understanding !x is a logical non-operator in C language. It booleans the value of x, that is, true changes to false, false changes to true. But be aware that truth and falsehood in C are represented by numerical values ​​rather than boolean types, non-zero is regarded as true, and only 0 is regarded as false. Therefore, !x deals with negative numbers the same as positive numbers and is considered true.

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

What does sum mean in C language? What does sum mean in C language? Apr 03, 2025 pm 02:36 PM

There is no built-in sum function in C for sum, but it can be implemented by: using a loop to accumulate elements one by one; using a pointer to access and accumulate elements one by one; for large data volumes, consider parallel calculations.

How to obtain real-time application and viewer data on the 58.com work page? How to obtain real-time application and viewer data on the 58.com work page? Apr 05, 2025 am 08:06 AM

How to obtain dynamic data of 58.com work page while crawling? When crawling a work page of 58.com using crawler tools, you may encounter this...

Copy and paste Love code Copy and paste Love code for free Copy and paste Love code Copy and paste Love code for free Apr 04, 2025 am 06:48 AM

Copying and pasting the code is not impossible, but it should be treated with caution. Dependencies such as environment, libraries, versions, etc. in the code may not match the current project, resulting in errors or unpredictable results. Be sure to ensure the context is consistent, including file paths, dependent libraries, and Python versions. Additionally, when copying and pasting the code for a specific library, you may need to install the library and its dependencies. Common errors include path errors, version conflicts, and inconsistent code styles. Performance optimization needs to be redesigned or refactored according to the original purpose and constraints of the code. It is crucial to understand and debug copied code, and do not copy and paste blindly.

See all articles