I have data with this shape
[[array([list([35, 76, 987, 23]),
list([76, 78, 54, 43]),
list([2376, 768, 84, 43])],
dtype=object)]]
I want to convert this data to a simple list like this
[35, 76, 987, 23, 76, 78, 54, 43, 2376, 768, 84, 43]
CodePudding user response:
if your array is inside those 2d list, then you can use this:
from numpy import array
from itertools import chain
a = [[array([list([35, 76, 987, 23]),
list([76, 78, 54, 43]),
list([2376, 768, 84, 43])],
dtype=object)]]
flat_list = list(chain(*a))
flat_list = (list(chain(*flat_list)))
flat_list = (list(chain(*flat_list)))
print(flat_list)
But I think your numpy
array is like this:
a = array([list([35, 76, 987, 23]),
list([76, 78, 54, 43]),
list([2376, 768, 84, 43])],
dtype=object)
then one time using of chain is enough like this:
flat_list = list(chain(*a))
print(flat_list)
CodePudding user response:
The cryptic answer:
list([[np.array([list([35, 76, 987, 23]),
list([76, 78, 54, 43]),
list([2376, 768, 84, 43])],
dtype=object)]][0][0].flatten())
Explanation:
from numpy import array
x = [[array([list([35, 76, 987, 23]),
list([76, 78, 54, 43]),
list([2376, 768, 84, 43])],
dtype=object)]]
Note that x
is a numpy array in a list, in a list. You may need to examine your life choices that have led you to arrive at this data structure :-)
Anyway, so x[0][0]
is the numpy array that you actually want to get your hands on. Numpy arrays have the handy flatten()
method, so:
x[0][0].flatten()
# -> array([35, 76, 987, 23, 76, 78, 54, 43, 2376, 768, 84, 43], dtype=object)
Now if you insist on getting a pure python list, just cast it like so:
list(x[0][0].flatten())
# -> [35, 76, 987, 23, 76, 78, 54, 43, 2376, 768, 84, 43]