looking for some solutions? You are welcome.

SOLVED: flatten a nested list with indices in python

Miffy:

I have a list ['','','',['',[['a','b']['c']]],[[['a','b'],['c']]],[[['d']]]]

I want to flatten the list with indices and the output should be as follows:

flat list=['','','','','a','b','c','a','b','c','d']
indices=[0,1,2,3,3,3,3,4,4,4,5]

How to do this?

I have tried this:

def flat(nums):
    res = []
    index = []
    for i in range(len(nums)):
        if isinstance(nums[i], list):
            res.extend(nums[i])
            index.extend([i]*len(nums[i]))
        else:
            res.append(nums[i])
            index.append(i)
    return res,index

But this doesn't work as expected.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent