基于Python中的模式将单个列表分成多个列表的最佳方法是什么?

时间:2016-01-22 00:28:52

标签: python nested-lists

我有一个非结构化列表作为输入,在我对它们进行多次分析之前我需要展平。一旦我得到每个输入的结果,将它们放回原始列表的相同结构中的最佳方法是什么?

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]]

3 个答案:

答案 0 :(得分:2)

这是一个使用Queue作为输出值和递归的解决方案:

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

copyStruct(inputList, iter(flattenedResults))

答案 1 :(得分:1)

迭代器对此有好处。保留原始列表的副本,以便维护其结构,然后构造展平列表的迭代器,递归原始列表(或其副本)并用迭代器中的下一个元素替换每个元素

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]]

答案 2 :(得分:0)

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

输出:

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]]