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

4

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

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

你能告诉我们更多关于这些计算的信息吗?不做展平处理可能行吗? - L3viathan
1
“chain” 不会将任意嵌套的列表(例如 ["e"])展平。 - donkopotamus
@donkopotamus 嗯,记住 chain.from_iterable([anything]) 只会给你 anything - Adam Smith
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Mostapha Roudsari
3个回答

2

以下是使用队列和递归的解决方案:

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

copyStruct(inputList, iter(flattenedResults))

不需要在这里使用队列,只需使用迭代器和 next(output_values) - Adam Smith
啊!感谢 @Adam Smith 提供的迭代器提示,但我认为这比使用嵌套函数更清晰。 - cr1msonB1ade
各有所好 :) 我更喜欢看到一个干净的闭包,而不是一个混乱的列表推导式。无论哪种方式都很好用。 - Adam Smith

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

你可以通过巧妙地使用默认参数,在一个函数中完成这个操作。 - TigerhawkT3
@TigerhawkT3 可能吧,但我认为闭包没有任何问题。在我看来,这使得代码更加简洁。 - Adam Smith

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接