What is the best way to split a single list into multiple template-based lists in Python?

I have an unstructured list as input, which I need to smooth out before running multiple analyzes on them. Once I have the results for each entry, what is the best way to return them to 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]]
+4
source share
3 answers

Here is a solution that uses a queue for 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))
+2
source

. , , , ( )

import copy

inputList = [["a", ["b","c","d"], [["e"]], "f"],["g"]]
flat_results = [0, 1, 2, 3, 4, 5, 6, 7]

def replace(orig, repl):
    new = copy.deepcopy(orig)
    repl = iter(repl)
    def _replace(lst):
        for idx, el in enumerate(lst):
            if isinstance(el, list):
                _replace(el)
            else:
                lst[idx] = next(repl)
    _replace(new)
    return new

replace(inputList, flat_results)
# [[0, [1, 2, 3], [[4]], 5], [6]]
+1
inputList = [["a", ["b","c","d"], [["e"]], "f"],["g"]]
flattenedList = magic(inputList)  # in python2, `magic` is compiler.ast.flatten

flatResults = calculations(flattenedList)

# now for the fun stuff

resultify(inputList, flatResults)

def resultify(inputList, flatResults, answer=None):
    if answer is None: answer = []
    if not inputList: return answer
    for elem in inputList:
        if not isinstance(elem, list): answer.append(flatResults.pop(0))
        else: answer.append(resultify(elem, flatResults, []))
    return answer

Output:

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

In [30]: flatResults = [1,2,3,4,5,6,7]

In [31]: resultify(inputList, flatResults)
Out[31]: [[1, [2, 3, 4], [[5]], 6], [7]]
0
source

Source: https://habr.com/ru/post/1625422/


All Articles