I have a situation where I have data that sometimes can be nested in multiple array layers.
Some times the data can be nested like:
[ [ 'green', 'blue', 'red' ] ]
Other times
[[[ ['green', 'blue', 'red' ] ]]]
I want to extract the array and return it, what would be the most pythonic way of doing this?
Numpy is your best friend as always :
>>> import numpy as np
>>> a = [[[ ['green', 'blue', 'red' ] ]]]
>>> print np.squeeze(a)
['green' 'blue' 'red']
The numpy function squeeze()
remove all the dimensions that are 1 in your array.
def get_nested_list(a):
if len(a) == 1 and isinstance(a[0], list):
return get_nested_list(a[0])
return a
Examples:
>>> get_nested_list([[[ ['green', 'blue', 'red' ] ]]])
['green', 'blue', 'red']
>>> get_nested_list([[[[1, 2],[3]]]])
[[1, 2], [3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With