【Python语法】reduce函数运算优先级的问题

reduce函数常用来对序列求和,但是在使用过程中,出了点小问题

首先看一个正常的求和表达式:

reduce(lambda x,y:x+y,range(1,101))  #对1~100的数求和

如果我想求1~10的平方和呢:

reduce(lambda x,y:x**2+y**2,range(1,11))

运行后发现结果不对:
25800022600047052140012507345164607168429796314974446082384073840147073775468094045329287185417173482087059144697336379483484925016241871310518944097995034059103738852836322303863800321890406457125

那重新写一下:

it=[item for item in map(lambda x:x**2,range(1,11))]
reduce(lambda x,y:x+y,it)

这次结果为:385

为什么呢,为什么直接在lambda的retuen语句中做平方运算就错了呢?

这个问题正好让我更深入的理解了reduce函数的运算规则,我们来看一下reduce的官方解释:

reduce(…)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a 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). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

这里我把x+y的表达式换成x2+y2,calculates展开就是:
(((1+2)2+32)2+42)2+52。所以才得到了一个数字很大的结果。

回头看reduce函数的参数列表:(function,sequence),它的作用是对sequence中的元素按照function规定的运算输出。因此,如果我们要使用reduce函数时务必注意,操作元素在执行function操作前就计算完毕。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值