[英]Python built-in function
is there a build-in equivalent of such function in python: 在python中有这样的函数的内置等价物:
def foo(a_func,a_list):
if len(a_list)==2:
return a_func(*[a_list])
else:
return a_func(a_list[0],foo(a_func,a_list[0:]))
in other words foo(lambda x,y:x+y,[1,2,3,4])
would add 1+2+3+4
and foo(lambda x,y:xy,[1,2,3,4])
would do ((1-2)-3)-4
etc. 换句话说, foo(lambda x,y:x+y,[1,2,3,4])
会加1+2+3+4
和foo(lambda x,y:xy,[1,2,3,4])
会做((1-2)-3)-4
等
And i know you can make it faster and prevent stack overflow ( :D ) but i think i remember such function but have no idea what the name is and dunno what to google. 我知道你可以让它更快,并防止堆栈溢出(:D),但我想我记得这样的功能,但不知道名称是什么,不知道该怎么去谷歌。
看起来你正在寻找https://docs.python.org/2/library/functools.html#functools.reduce(AKA https://docs.python.org/2/library/functions.html#reduce in Python 2),假设你的代码和a_list[0:]
存在一个错误,你实际上是指a_list[1:]
(否则你正在寻找一个永无止境的循环:-)。
You are describing the reduce()
function ; 您正在描述reduce()
函数 ; in Python 3 it has been moved to the functools
module : 在Python 3中它已被移动到functools
模块 :
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. 应用的两个参数函数累计到序列的项目,由左到右,这样的顺序,以减少单个值。 For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates((((1+2)+3)+4)+5)
. 例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
计算((((1+2)+3)+4)+5)
。
You can of course use any callable; 你当然可以使用任何可调用的; the operator
module offers several handy options: operator
模块提供了几个方便的选项:
>>> from functools import reduce
>>> import operator
>>> reduce(operator.add, [1,2,3,4])
10
>>> reduce(operator.sub, [1,2,3,4])
-8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.