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

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

问题描述

常规函数可以在其定义中包含对自身的调用,没问题.我不知道如何使用lambda函数来执行此操作,原因很简单,因为lambda函数没有可引用的名称.有办法吗?怎么样?

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)

或替代地,对于python的早期版本:

or alternately, for earlier versions of python:

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

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

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天全站免登陆