如何递归整理列表?

时间:2019-04-01 02:54:07

标签: python

我想拼合列表,例如我除了要关注以下内容之外:

[[['I003', 'I004', 'I005'], ['I007', 'I008', 'I009'], ['I00B'], ['I00D']], ['I003', 'I004', 'I005'], 'I003', 'I004']

进入:

['I003', 'I004', 'I00B', 'I007', 'I008', 'I009', 'I005', 'I00D']

我的代码有效,但嵌套限制为3:

def flatten(lst):
    res = []
    for sublist in lst:
        if isinstance(sublist, list):
            for sublist2 in sublist:
                if isinstance(sublist2, list):
                    for sublist3 in sublist:
                        if isinstance(sublist3, list):
                            for item in sublist3:
                                res.append(item)
                        else:
                            res.append(sublist3)
                else:
                    res.append(sublist2)
        else:
            res.append(sublist)
    res = list(set(res))
    return res

我知道可以递归完成,但是我想不出

0 个答案:

没有答案