python中seq是什么_等同于Python中的F#的Seq.scan()方法?

Is there a function like a F#'s Seq.scan() in Python?

I want to do some cumsum() or cumproduct() kind of things without looping.

解决方案

Ignacio's solution is almost right I think, but requires a operator of type ('a -> 'a -> 'a) and doesn't yield the first element.

def scan(f, state, it):

for x in it:

state = f(state, x)

yield state

# test

>>> snoc = lambda xs,x: xs+[x]

>>> list(scan(snoc, [], 'abcd'))

[['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']]

>>> list(scan(operator.add, 0, [1,2,3]))

[1,3,6]

Specifically, the type of Seq.scan is

('State -> 'T -> 'State) -> 'State -> seq -> seq

The default approach in Python is to write a scan with the type

('State -> 'State -> 'State) -> seq -> seq

This comes from the way that Python specifies reduce, which has the same type by default.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值