等同于Python中的F#的Seq.scan()方法? [英] Equivalent to F#’s Seq.scan() method in Python?
本文介绍了等同于Python中的F#的Seq.scan()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中是否有像F#的 Seq.scan()
这样的函数?
我想做一些 cumsum()
或 cumproduct()
没有循环的东西。
'a - >'a)的运算符,并且不会产生第一个元素。
def scan(f,state,it):
for x:
state = f (状态,x)
收益状态
#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]
具体来说, Seq.scan
的类型是
('State - >'T - >'State) - > '州 - > SEQ< T> - > SEQ<状态>
Python中的默认方法是编写 scan
类型
('State - >'State - >'State) - > SEQ<状态> - > SEQ<状态>
这来自Python指定 reduce
,默认情况下它具有相同的类型。
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<'T> -> seq<'State>
The default approach in Python is to write a scan
with the type
('State -> 'State -> 'State) -> seq<'State> -> seq<'State>
This comes from the way that Python specifies reduce
, which has the same type by default.
这篇关于等同于Python中的F#的Seq.scan()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文