Home > Software engineering >  alternately flatten values of nested list
alternately flatten values of nested list

Time:02-18

Is there a way to flatten values of a nested list but alternately?

example:

nested_list = [[1, 3, 5], [2, 4]]

my expected output would be:

[1, 2, 3, 4, 5]

CodePudding user response:

Use hstack from numpy

import numpy as np
nested_list = [[1, 3, 5], [2, 4]]
new_nested_list = np.hstack(nested_list)

now new_nested_list is equal to [1 3 5 2 4]

CodePudding user response:

You can do it without numpy using iterators and keep track when the list stops growing:

nested_list = [[1, 3, 5], [2, 4]]

# create a list of iterators per sublists
k = [iter(sublist) for sublist in nested_list]

# collect values
res = []

# choose a value thats not inside your lists
sentinel = None

growing = True
while growing:
    growing = False
    for i in k:
        # returns sentinel (None) if sublist no longer iterable
        u = next(i, sentinel)

        # add if it got a value
        if u != sentinel:
            growing = True
            res.append(u)
        
print(res)  # [1,2,3,4,5]

IF you have None values in your list, you need to choose another sentinel value.

  • Related