Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

python - Use None as initial for itertools.accumulate

It'd be nice to use itertools.accumulate with initial=None to literally mean that it should start with None.

For example:

from typing import Optional, Iterable
from itertools import islice, accumulate

def f(a: Optional[A], b: B) -> A:
    pass

b_s: Iterable[B] = [...]
_a_s = accumulate(b_s, f, initial=None)  # doesn't work!
a_s = list(islice(_a_s, 1, None))

This fails because initial=None tells accumulate to use the first element as the initial and go from there, so f will end up being called with two B arguments.

Does anyone know an easy way around this?
My current plan is to use False, but then I have a bunch more hoops to jump through explaining what I'm doing to MyPy.

question from:https://stackoverflow.com/questions/66056688/use-none-as-initial-for-itertools-accumulate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your best option is probably to chain the value onto the input iterable:

output = accumulate(chain([None], iterable), f)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...