0

For example,

list1 = [1,2,[5,[6],8],7]
n = 3

How can i make so it removes n elements while accessing the sublists? Considering n = 3 it would remove 1,2 and the 5 out of [5,[6],8], not the entire sublist, making it become [[6],8] I know i can access all sublist levels by using recursion:

list1 = [1,2,[5,[6],8],7]

def print_all(l):
    for el in l:
        if type(el) == list:
            print_all(el)
        else:
            print(el)
    return
print_all(list1)

the output is:

1
2
5
6
8
7

Now I'm stuck on the removing part, any kind of help would be much appreciated. Thank you!

zamir
  • 2,144
  • 1
  • 11
  • 23
Zolak
  • 23
  • 3
  • 4
    flatten the list first, then remove elements from the flat list as required – Sayse Dec 03 '19 at 14:53
  • Do you want to remove only numbers, keeping the lists inside list? For example `[1,2,[5,[6],8],7]` and `n=4` the result will be `[[[], 8], 7]` ? – Andrej Kesely Dec 03 '19 at 15:14

1 Answers1

-1

You can first flatten the original input, find the target values to be removed, and then recursively remove the selected values:

def flatten(d, c = 0):
   for i, a in enumerate(d):
     yield from ([(a, i, c)] if not isinstance(a, list) else flatten(a, c+1))

def l_remove(d, vals, c = 0):
    return [l_remove(a, vals, c+1) if isinstance(a, list) else a for i, a in enumerate(d) \
      if (a, i, c) not in vals]

list1, n = [1,2,[5,[6],8],7], 3
selected = l_remove(list1, list(flatten(list1))[:n])

Output:

[[[6], 8], 7]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102