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]]
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))
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), [])
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]]
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))
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), [])