Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to return an array that is nested in multiple arrays

Tags:

python

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?

like image 806
Nirma Avatar asked Nov 28 '12 16:11

Nirma


2 Answers

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.

like image 100
Thomas Leonard Avatar answered Sep 17 '22 10:09

Thomas Leonard


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]]
like image 23
Steven Rumbalski Avatar answered Sep 19 '22 10:09

Steven Rumbalski