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?

4
  • 1
    Are there any other elements in the parent lists? or are you simply looking to strip the excess nesting? Commented Nov 28, 2012 at 16:34
  • See stackoverflow.com/questions/952914/… Commented Nov 28, 2012 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... Commented Nov 28, 2012 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. Commented Nov 28, 2012 at 16:41

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't agree with your best friend as always - but +1
:) why? Numpy has ever let you down in the past?
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]]

4 Comments

This is useful only if a single element is nested.
@AshRj: Now handles multi-element lists with some sanity.
I am assuming the first test is to check for empty lists ? But there already is a check len(a)==1 which will handle empty lists ..
The len(a)==1 should be before the isinstance check for it to handle empty lists
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

6 Comments

@AshRj, what would be the expected output in that case though?
Depending on state of the program, you could want to return either the first list or the second list.
strip([['a']]) -> RuntimeError: maximum recursion depth exceeded
true about the single element lists, I added an instance check
@COpython The OP hasnt specified that there will only be one element :) But ,anyways, point taken.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.