Is there a way to flatten values of a nested list but alternately?
example:
JavaScript
x
2
1
nested_list = [[1, 3, 5], [2, 4]]
2
my expected output would be:
JavaScript
1
2
1
[1, 2, 3, 4, 5]
2
Advertisement
Answer
You can do it without numpy using iterators and keep track when the list stops growing:
JavaScript
1
25
25
1
nested_list = [[1, 3, 5], [2, 4]]
2
3
# create a list of iterators per sublists
4
k = [iter(sublist) for sublist in nested_list]
5
6
# collect values
7
res = []
8
9
# choose a value thats not inside your lists
10
sentinel = None
11
12
growing = True
13
while growing:
14
growing = False
15
for i in k:
16
# returns sentinel (None) if sublist no longer iterable
17
u = next(i, sentinel)
18
19
# add if it got a value
20
if u != sentinel:
21
growing = True
22
res.append(u)
23
24
print(res) # [1,2,3,4,5]
25
IF you have None
values in your list, you need to choose another sentinel
value.