lambda 函数可以在 Python 中递归调用自身吗? [英] Can a lambda function call itself recursively in Python?

查看:32
本文介绍了lambda 函数可以在 Python 中递归调用自身吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常规函数可以在其定义中包含对自身的调用,没问题.我不知道如何用 lambda 函数来做这件事,原因很简单,即 lambda 函数没有可引用的名称.有没有办法做到这一点?怎么样?

解决方案

我能想到的唯一方法就是为函数命名:

fact = lambda x: 1 if x == 0 else x * fact(x-1)

或者,对于早期版本的 python:

fact = lambda x: x == 0 and 1 or x * fact(x-1)

更新:使用其他答案中的想法,我能够将阶乘函数楔入一个未命名的 lambda 中:

<预><代码>>>>map(lambda n: (lambda f, *a: f(f, *a))(lambda rec, n: 1 if n == 0 else n*rec(rec, n-1), n), range(10))[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

所以这是可能的,但并不真正推荐!

A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?

解决方案

The only way I can think of to do this amounts to giving the function a name:

fact = lambda x: 1 if x == 0 else x * fact(x-1)

or alternately, for earlier versions of python:

fact = lambda x: x == 0 and 1 or x * fact(x-1)

Update: using the ideas from the other answers, I was able to wedge the factorial function into a single unnamed lambda:

>>> map(lambda n: (lambda f, *a: f(f, *a))(lambda rec, n: 1 if n == 0 else n*rec(rec, n-1), n), range(10))
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

So it's possible, but not really recommended!

这篇关于lambda 函数可以在 Python 中递归调用自身吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆