Expressed as a generator function:
def neighborhood(iterable):
iterator = iter(iterable)
prev_item = None
current_item = next(iterator) # throws StopIteration if empty.
for next_item in iterator:
yield (prev_item, current_item, next_item)
prev_item = current_item
current_item = next_item
yield (prev_item, current_item, None)
Usage:
for prev,item,next in neighborhood(l):
print prev, item, next
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…