Python: Function to flatten generator containing another generator
The easiest way is a recursive flattening function. Assuming you want to descend into every iterable except for strings, you could do this:
def flatten(it):
for x in it:
if (isinstance(x, collections.Iterable) and
not isinstance(x, str)):
for y in flatten(x):
yield y
else:
yield x
Starting from Python 3.3, you can also write
def flatten(it):
for x in it:
if (isinstance(x, collections.Iterable) and
not isinstance(x, str)):
yield from flatten(x)
else:
yield x