简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM