Home > Software design >  Iterate through a nested list and pick certain elements and create a new list
Iterate through a nested list and pick certain elements and create a new list

Time:10-31

An example:

list = [[2, 1, 2, 3, 4],
       [0, 4, 5],
       [1, 8, 9]]

So the first index inside a nested list decides which following numbers will be put into an unnested list.

[2, 1, 2, 3, 4] -> 2: so 1 and 2 gets picked up
[0, 4, 5] -> 0: no number gets picked up
[1, 8, 9] -> 1; number 8 gets picked up

Output would be:

[1, 2, 8]

This is what I have so far:

def nested_list(numbers):
    if isinstance(numbers[0], list):
        if numbers[0][0] > 0:
            nested_list(numbers[0][1:numbers[0][0]   1])
    else:
        numbers = list(numbers[0])

    return numbers   nested_list(numbers[1:])

I try to get the list through recursion but something is wrong. What am I missing or could this be done even without recursion ?

CodePudding user response:

list1=[[2, 1, 2, 3, 4],
       [0, 4, 5],
       [1, 8, 9]]
list2= []

for nested_list in list1:
    for i in range(nested_list[0]):
        list2.append(nested_list[i 1])

CodePudding user response:

You can try List-comprehension:

>>> [sub[i] for sub in lst for i in range(1, sub[0] 1) ]
[1, 2, 8]

PS: The solution expects each sublist to be a non-empty list, else it will throw IndexError exception due to sub[0].

CodePudding user response:

You try using list comprehension with tuple unpacking here.

[val for idx, *rem in lst for val in rem[:idx]] 
# [1, 2, 8]

NB This solution assumes you would always have a sub-list of size 1 or greater. We can filter out empty sub-lists using filter(None, lst)

CodePudding user response:

Another list comprehension

sum([x[1:x[0]   1] for x in arr], [])
# [1, 2, 8]
  • Related