I want to write a function that extracts elements from deep nested tuples and lists, say I have something like this
l = (\'THIS\', [(\'THAT\', [\'a\', \'b\']),
It will be good to separate the concerns of "flattening" and "filtering". Decoupled code is easier to write and easier to test. So let's first write a "flattener" using recursion:
from collections import Iterable
def flatten(collection):
for x in collection:
if isinstance(x, Iterable) and not isinstance(x, str):
yield from flatten(x)
else:
yield x
Then extract and blacklist:
def extract(data, exclude=()):
yield from (x for x in flatten(data) if x not in exclude)
L = ('THIS', [('THAT', ['a', 'b']), 'c', ('THAT', ['d', 'e', 'f'])])
print(*extract(L, exclude={'THIS', 'THAT'}))