加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python内置函数

发布时间:2020-12-20 11:40:56 所属栏目: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:])) 换句话说,foo(lambda x,y:x y,[1,2,3,4])会增加1 2 3 4 和foo(lambda x,y:x-y,4])
在 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 4
和foo(lambda x,y:x-y,4])会做((1-2)-3)-4等

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

解决方法

你在描述 reduce() function;在Python 3中,它已被移至 functools module:

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,4,5]) calculates ((((1+2)+3)+4)+5).

你当然可以使用任何可调用的; operator module提供了几个方便的选择:

>>> from functools import reduce
>>> import operator
>>> reduce(operator.add,4])
10
>>> reduce(operator.sub,4])
-8

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读