python中累加函数_定义累加?(高阶函数)

你似乎想要得到:每个序列的第一个元素的列表,可以是[s[0] for s in sequences],并且

每个序列的剩余元素的列表,可以是[s[1:] for s in sequences]。在

总共:def accumulate(op, init, seq):

if not seq:

return init

else:

return op(seq[0], accumulate(op, init, seq[1:]))

def accumulate_n(op, init, sequences):

if (not sequences) or (not sequences[0]):

return type(sequences)()

else:

heads = [s[0] for s in sequences]

tails = [s[1:] for s in sequences]

return ([accumulate(op, init, heads)]

+ accumulate_n(op, init, tails))

但是,为了它的价值,我将按行而不是按列执行,并要求init本身是一个序列:

^{pr2}$

清洁要求:def accumulate_n(op, init, sequences):

for s in sequences:

init = [op(x, y) for x, y in zip(init, s)]

return init

最后,使用functools.reduce:def zipper(op):

return lambda xs, ys: [op(x, y) for x, y in zip(xs, ys)]

def accumulate_n(op, init, sequences):

return reduce(zipper(op), sequences, init)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值