0

I want to flatten the list:

exampleArray = [[[151.68694121866872]], 
                [[101.59534468349297]], 
                [[72.16055999176308]]]

to:

[151.68694121866872, 101.59534468349297, 72.16055999176308]

Right now I am doing this:

resultArray= list(chain.from_iterable(list(chain.from_iterable(exampleArray))))

Even though it works I wanted to know if there's a better way.

5
  • what is chain.from_iterable() ? Commented Oct 15, 2012 at 9:50
  • It is itertools.chain.from_iterable. Commented Oct 15, 2012 at 9:53
  • 2
    I guess then just list(chain.from_iterable(chain.from_iterable(lis))) is enough, no need of that list() call. ` Commented Oct 15, 2012 at 9:57
  • is it always just a list containing single element (nested) sublists? Commented Oct 15, 2012 at 9:57
  • This is very close: Flatten (an irregular) list of lists in Python Commented Oct 15, 2012 at 10:01

5 Answers 5

2

How about

result = [x[0][0] for x in exampleArray]
Sign up to request clarification or add additional context in comments.

1 Comment

Very good specific example. Not the best general one though, obviously.
1
In [6]: from itertools import chain

In [7]: lis=[[[151.68694121866872]], [[101.59534468349297]], [[72.16055999176308]]]

In [8]: list(chain(*(chain(*lis))))

Out[8]: [151.68694121866872, 101.59534468349297, 72.16055999176308]

Comments

1

You don't need to convert the itertools.chain object (an iterable) into a list:

resultArray= list(chain.from_iterable(list(chain.from_iterable(exampleArray))))
# could be rewritten as
resultArray= list(chain.from_iterable(chain.from_iterable(exampleArray)))

.

You could write a deepness function using recursion:

def deep_chain_from_iterable(it, n):
    if n == 0:
        return list(it)
    else:
        return deep_chain_from_iterable(itertools.chain.from_iterable(it),n-1)

deep_chain_from_iterable(exampleArray, 2)

Comments

1

There isn't a better way, this is the most recommended way. See official recipes

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

1 Comment

thanks just wanted to see if there was will remove the extra list I added to the code
0

For fixed level of depth (as in example) you can just sum enough times:

sum(sum(listoflistsoflists, []), [])

Comments

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.