Ad

What Is The Best Way To Separate A Single List Into Multiple Lists Based On A Pattern In Python?

- 1 answer

I have an unstructured list as an input which I need to flatten before I run several analysis on them. Once I have the results for each input what it the best way to put them back in the same structure of the original list?

inputList = [["a", ["b","c","d"], [["e"]], "f"],["g"]]

flattenedList = myFlattenListFunction(inputList)

# a number of calculations based on the inputList
# ...

flattenedResults = [0, 1, 2, 3, 4, 5, 6, 7]

#What is the best solution to restructure the results to match the inputLists?
[[1, [2,3,4], [[5]], 6], [7]]
Ad

Answer

Here is a solution using a Queue for the output values and recursion:

def copyStruct(inputStruct, outputValues):
    return [copyStruct(subList, outputValues)
            if isinstance(subList, list)
            else next(outputValues)
            for subList in inputStruct]

copyStruct(inputList, iter(flattenedResults))
Ad
source: stackoverflow.com
Ad