lihuanshuai
9/28/2017 - 7:12 AM

Previous and next values inside a loop

from itertools import tee, islice as slice, chain, izip as zip

def previous_and_next(iterable, fill_value=None):
    prevs, items, nexts = tee(iterable, 3)
    prevs = chain([fill_value], prevs)
    nexts = chain(slice(nexts, 1, None), [fill_value])
    return zip(prevs, items, nexts)