flatten list in python

后端 未结 5 1564
南旧
南旧 2021-01-26 01:04

I want to flatten the list:

exampleArray = [[[151.68694121866872]], 
                [[101.59534468349297]], 
                [[72.16055999176308]]]
5条回答
  •  孤城傲影
    2021-01-26 01:49

    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)
    

提交回复
热议问题