3

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]]
4
  • What have you tried? >>> [2,4,array([3.])] Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'array' is not defined Commented Dec 7, 2012 at 9:39
  • @JohnMee Maybe numpy.array. Commented Dec 7, 2012 at 9:40
  • @iMom0 hmm, given the duplicate? you might be right. Still banging his drum but... you want to help him? Commented Dec 7, 2012 at 9:44
  • With variable lengths and nesting of numbers and lists I would try to make a recursive approach. Commented Dec 7, 2012 at 9:46

2 Answers 2

3
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))
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

This will be very slow if you have many elements to deal with. With each step in the summation, a new list is allocated containing all elements seen so far. End result is worst-case O(n**2) time in the number of elements.
Premature optimization. If performance on long lists were a requirement, he would have said so. My solution is both more general and easier to read, and thus maintain, than your solution. Though yours certainly is better if there is a chance that there are many elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.