1

I have the following list instance:

import numpy as np
l = [4.0, 0.0, np.array([0.0, 1.0, 2.0, 3.0, -3.0, -2.0, -1.0]), np.array([2.0, 4.0, 0.0])]

Is it too much trouble to get a single list of the following values:

[4.0, 0.0, 0.0, 1.0, 2.0, 3.0, -3.0, -2.0, -1.0, 2.0, 4.0, 0.0]

i.e. a flattened list.

Thanks for any help here.

ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • It's no different to flattening a nested list. What is the error? – roganjosh Apr 24 '19 at 12:33
  • Possible duplicate of [How can I flatten lists without splitting strings?](https://stackoverflow.com/questions/5286541/how-can-i-flatten-lists-without-splitting-strings) – Bram Vanroy Apr 24 '19 at 12:39

2 Answers2

4

Try np.hstack(l), which horizontally stacks 1D arrays, lists (iterables), and scalars. https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html

Ben
  • 9,184
  • 1
  • 43
  • 56
1

You can try using ndarray.tolist() to convert the arrays to list objects, and then adding them to the list, for example:

a1 = np.array([0,1,2,3])
l1 = [-2,-1]

a1_list = a1.tolist()
l1.extend(a1_list)

Will return a flattened list from -2 to 3. That is in case you want to have the elements in a list object, but the arrays object is in most cases preferred to work with numbers.