recursive function for extract elements from deep nested lists/tuples

后端 未结 4 472
后悔当初
后悔当初 2021-01-21 18:07

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\']),          


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 18:45

    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'}))
    

提交回复
热议问题