Is there a way to reshape a list ? Just like with an array, my problem is the following: I'd like to have my list L (see below) to have a shape (6,) is there a formula to achieve it ? (I have a similar problem with a code where I need to append several times and at the end I get a list shape (1,1,..,23) and I want to get (23,).
import numpy as np
L = [[1,2,3,4,5,6]]
L1 = [1,2,3,4,5,6]
print(np.shape(L))
print(np.shape(L1))
The output is :
(1,6)
and
(6,)
CodePudding user response:
I think you are looking for the numpy.ndarray.flatten()
equivalent for python lists. As far as I know, there does not exist such functionality out of the box. However, is easily done with list expressions:
L1 = [item for sublist in L for item in sublist]
If you can use numpy (as your example suggest), the most straight-forward solution is to apply the flatten method on your arrays:
L = [[1,2,3,4,5,6]]
L = np.array(L)
L1 = L.flatten()
Note that you then switch to numpy arrays.