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.

moooeeeep
  • 30,004
  • 18
  • 92
  • 173
user1741339
  • 467
  • 2
  • 6
  • 11

5 Answers5

2

How about

result = [x[0][0] for x in exampleArray]
waitingkuo
  • 80,738
  • 23
  • 108
  • 117
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]
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
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)
Meitham
  • 8,311
  • 4
  • 32
  • 43
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)
Andy Hayden
  • 328,850
  • 93
  • 598
  • 514
0

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

sum(sum(listoflistsoflists, []), [])
mechmind
  • 1,702
  • 13
  • 11