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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With