recursive function for extract elements from deep nested lists/tuples

后端 未结 4 664
后悔当初
后悔当初 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:39

    This iterative function should do the trick alongside the .extend() list operator.

    def func(lst):
        new_lst = []
        for i in lst:
            if i != 'THAT' and i != 'THIS':
                if type(i) == list or type(i) == tuple: 
                    new_lst.extend(func(i))
                else: new_lst.append(i)
        return new_lst
    
    l = ('THIS', [('THAT', ['a', 'b']), 'c', ('THAT', ['dk', 'e', 'f'])])
    print(func(l))
    

    ['a', 'b', 'c', 'dk', 'e', 'f']

提交回复
热议问题