为了账号安全,请及时绑定邮箱和手机立即绑定

reduce()初值的默认值是多少?

reduce()的初值在函数为求和时似乎是0,在求成绩时似乎为1,如果不设置初值,这个初值是根据函数的计算式自动确定,还是在不设置的情况下不参与运算?

正在回答

3 回答

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
reduce(函数, 列表, 初始值) 
reduce()传入的函数 f 必须接收两个参数
任务:
Python内置了求和函数sum(),但没有求积的函数,请利用recude()来求积:
输入:[2, 4, 5, 7, 12]
输出:2*4*5*7*12的结果
'''
L = [2, 4, 5, 7, 12]
def f(x, y):              # 函数f 必须接受2个参数
    return x * y    # 2个相邻参数进行相乘
print reduce(f, L)


0 回复 有任何疑惑可以回复我~

初始值是None,以下是官方文档的定义及解释:

def reduce(function, iterable, initializer=None):
   it = iter(iterable)
   if initializer is None:
       try:
           initializer = next(it)
       except StopIteration:
           raise TypeError('reduce() of empty sequence with no initial value')
   accum_value = initializer
   for x in it:
       accum_value = function(accum_value, x)
   return accum_value
文档地址:https://docs.python.org/2.7/library/functions.html#reduce

1 回复 有任何疑惑可以回复我~

???你有没有例子,reduce()的初始值应该是根据reduce(f,list)中的list的值来确定的

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
python进阶
  • 参与学习       255532    人
  • 解答问题       3038    个

学习函数式、模块和面向对象编程,掌握Python高级程序设计

进入课程

reduce()初值的默认值是多少?

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号