Home > database >  Flattening unknown nesting level of list with help of looping in Python
Flattening unknown nesting level of list with help of looping in Python

Time:10-08

Can you please help me with this problem? I need to solve it with help of looping.

Statement

Your input is a list of lists with unknown nesting level. Could be like:

[
    [1, 2],
    [
        3,
        [4, 5],
    ],
    6,
    7,
]

Your challenge is to reshape it into a single list like that:

[1, 2, 3, 4, 5, 6, 7]

My code is :

import json

data = json.loads(input())
#WRITE YOUR CODE HERE 
list_data = list(data) 
flat_list = [item for items in list_data for item in items] 
print(flat_list)

TypeError: 'int' object is not iterable

CodePudding user response:

Try recursive approach:

lst = [[1, 2],[3,[4, 5],],6,7]

def flat_list(lst, res):
    for l in lst:
        if isinstance(l, list):
            flat_list(l, res)
        else:
            res.append(l)
            
result = []
flat_list(lst, result)
print(result)

Output:

[1, 2, 3, 4, 5, 6, 7]

Update: (use looping without recursive approach)

lst = [[1, 2],[3,[4, 5],],6,7]

res = []
for l in lst:
    tmp = [l]
    while tmp != []:
        for i in tmp:
            if isinstance(i, list):
                for j in i:
                    tmp.append(j)
            else:
                res.append(i)
            tmp = tmp[1:]
print(res)
# [1, 2, 3, 4, 5, 6, 7]

CodePudding user response:

Here is a stack-based approach:

lst = [[1, 2], [3, [4, 5], ], 6, 7]

stack = lst[::-1]
res = []

while stack:
    item = stack.pop()
    if isinstance(item, list):
        for x in item[::-1]:
            stack.append(x)
    else:
        res.append(item)

print(res)
  • Related