flatten a list of variable length arrays

Question:

how to convert this:

[2, 4, array([ 3.]), array([ 4.]), array([ 5.,  4.])]

to

[2,4,3,4,5,4]

I’ve tried searching but the solutions work for

[array([ 2.]), array([ 4.]), array([ 3.]), array([ 4.]), array([ 5.,  4.])]

and

[[2],[4],[3],[4],[5,4]]
Asked By: Sajid

||

Answers:

import itertools
import numpy as np

a = [2, 4, array([ 3.]), array([ 4.]), array([ 5.,  4.])]
list(itertools.chain.from_iterable(np.asarray(b).ravel() for b in a))
Answered By: Michael J. Barber

I like to use sum for flattening things. In your case, you want to convert the arrays to lists and the numbers to lists of numbers, first. Thus if the array is in a:

sum((list(x) if hasattr(x, '__iter__') else [x] for x in a), [])
Answered By: Gurgeh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.