Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...