Reputation: 5388
Suppose, I have a list,
[(1,2), (3, 4)].
I will print 1 + 2 and 3 + 4 if all elements of the list are tuples. But if any one of the elements is also a list, then I add 1 to every element of the inner list and every element of that inner list is appended to the parent list. eg.
list = [(1,2), [(3, 4), (5, 6)]],
becomes
[(1, 2), (3, 4, 1), (5, 6, 1)].
Again, if the inner list has a list as an element, we repeat the same thing. eg.
[(1,2), [(3, 4), (5, 6), [(7, 8)]]]
first becomes
[(1,2), [(3, 4), (5, 6), (7, 8, 1)]]
then finally becomes,
[(1,2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1)].
How do I do this procedure to such a list, whose nesting level(as in list in a list in a list....) is not known ?
The code I used to generate this list is as follows:
def possible_sums(a):
if a == 2:
return [(1, 1)]
list_l = list(((a - 1, 1), ))
list_l.append(possible_sums(a-1))
return list_l
print(possible_sums(8))
Upvotes: 1
Views: 465
Reputation: 814
nested_lst = [(1,2), [(3, 4), (5, 6), [(7, 8)]] ,(2,3),[(6,7)]]
output = []
def de_nestify(lst,lvl):
if len(lst) != 0:
for item in lst:
if isinstance(item, list):
lvl += 1
de_nestify(item,lvl)
lvl = 0 #reset nesting lvl
else:
item += (1,)*lvl
output.append(item)
de_nestify(nested_lst,0)
print(output)
#[(1, 2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1), (2, 3), (6, 7, 1)]
Upvotes: 1
Reputation: 60994
This solution uses nested generators. We loop through the items of our list, checking their types. Whenever we see a list
, we recursively call flatten
on that list, and add 1
to the end of each output. If item
is a tuple, we just yield it. Then outside flatten
, we iterate though the generator to build a list.
def flattener(lst):
for item in lst:
if isinstance(item, list):
gen = flattener(item)
for item in gen:
yield item + (1,)
elif isinstance(item, tuple):
yield item
print(list(flattener([(1,2), [(3, 4), (5, 6), [(7, 8)]], [(5, 6, 7), [(1, 2)]]])))
# [(1, 2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1), (5, 6, 7, 1), (1, 2, 1, 1)]
Upvotes: 3