Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get pairwise iterator with additional item in the end

The goal: e.g. given finite iterator p0, p1, ..., pn turn into (p0, p1), (p1, p2), ..., (pn-1, pn), (pn, None) — iterator through pairs of consecutive items with special last item.

pairwise() function exists in the documentation as example of itertools usage:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

But I want additionally add yet another item to the end of iterator (if it is finite) with some default value for the second element of pair (e.g., None).

How to efficiently implement this additional functionality?

like image 238
kupgov Avatar asked Dec 24 '22 11:12

kupgov


1 Answers

Using itertools.zip_longest:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip_longest(a, b)

When one of the input iterators runs out, zip_longest pads it with a filler value, which defaults to None.

like image 95
user2357112 supports Monica Avatar answered Feb 01 '23 13:02

user2357112 supports Monica