5

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?

Nirma
  • 5,640
  • 4
  • 35
  • 47
  • 1
    Are there any other elements in the parent lists? or are you simply looking to strip the excess nesting? – Martijn Pieters Nov 28 '12 at 16:34
  • See http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – Praveen Gollakota Nov 28 '12 at 16:35
  • 1
    Stripping the "nesting" is easy - but I'd look more to not having it in the first place ie, if unpredictable results - then there's a flaw somewhere that needs addressing... – Jon Clements Nov 28 '12 at 16:36
  • @JonClements I agree with you on your approach of not having bad data in the first place but for the time being I need to strip the nesting. – Nirma Nov 28 '12 at 16:41

3 Answers3

3
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]]
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
3

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.

Thomas Leonard
  • 1,047
  • 11
  • 25
0

recursive solution:

def strip(a):
    if len(a)==1:
        if isinstance(a[0], list):
            a=a[0]
            return strip(a)
        else:
            return a
    return a
Cameron Sparr
  • 3,925
  • 2
  • 22
  • 31