You can download this code by clicking the button below.
This code is now available for download.
This function extends the built-in `zip_longest` function to handle iterable objects and convert the result into a flattened iterator. It uses `collections.deque` to ensure that each iterable is a `deque` type, so that it can be padded as needed.
Technology Stack : itertools, collections
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
from itertools import zip_longest
from collections import deque
def flatten(input):
for item in input:
if isinstance(item, deque):
for subitem in flatten(item):
yield subitem
else:
yield item
def ensure_deque(input):
if isinstance(input, deque):
return input
else:
return deque(input)
iterables = [ensure_deque(arg) for arg in args]
max_length = max(len(it) for it in iterables)
padded_iterables = [deque(list(it) + [fillvalue] * (max_length - len(it))) for it in iterables]
for item in flatten(padded_iterables):
yield item