繁体   English   中英

Python内置函数

[英]Python built-in function

在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:]))

换句话说, foo(lambda x,y:x+y,[1,2,3,4])会加1+2+3+4foo(lambda x,y:xy,[1,2,3,4])会做((1-2)-3)-4

我知道你可以让它更快,并防止堆栈溢出(:D),但我想我记得这样的功能,但不知道名称是什么,不知道该怎么去谷歌。

它的reduce功能是什么!

从左到右累加两个参数的函数到iterable项,以便将iterable减少为单个值

看起来你正在寻找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:] (否则你正在寻找一个永无止境的循环:-)。

您正在描述reduce()函数 ; 在Python 3中它已被移动到functools模块

应用的两个参数函数累计到序列的项目,由左到右,这样的顺序,以减少单个值。 例如, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])计算((((1+2)+3)+4)+5)

你当然可以使用任何可调用的; 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM