[英]Does Python have a `nest` function like Mathematica?
Mathematica has a convenient Nest
function for repeatedly evaluating f(f(f(f(...f(n)))))
. Mathematica 有一个方便的
Nest
function 用于重复评估f(f(f(f(...f(n)))))
。 Not something you need every day, but occasionally useful.不是你每天都需要的东西,但偶尔有用。 Here is a trivial implementation:
这是一个简单的实现:
def nest(f, expr, n):
assert n >= 0
if n == 0:
return expr
else:
return f(nest(f, expr, n - 1))
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676
Is there a Pythonic way to do this?有没有一种 Pythonic 的方法来做到这一点?
Perhaps if you like these sorts of things, you can look into functools.reduce
:也许如果你喜欢这些东西,你可以看看
functools.reduce
:
from functools import reduce
def nest(f, expr, n):
return reduce(lambda x, _: f(x), range(n), expr)
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676
Talking Pythonic, which is a bit of an opinion-based concept, I'd say a simple iterative implementation is more readable ( Readability being a core Python principle ) than reduce
-based or recursive approaches:谈论 Pythonic,这是一个基于意见的概念,我想说一个简单的迭代实现比基于
reduce
或递归的方法更具可读性(可读性是核心 Python 原则):
def nest(f, expr, n):
for _ in range(n):
expr = f(expr)
return expr
Certainly, I will not have to stare down what's happening here as much as in the other cases.当然,我不必像在其他情况下那样盯着这里发生的事情。 If it is, however, brevity you're after, you can go with a conditional expression:
但是,如果您想要简洁,您可以使用条件表达式 go :
def nest(f, expr, n):
return f(nest(f, expr, n - 1)) if n else expr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.