如何在Python中将压缩列表扩展为完整列表?

时间:2015-06-20 04:50:02

标签: python list recursion

我有一个像(可能更大)的压缩列表:

[[[1, [2, 3], [3, 2]]], [[2, [1, 3], [3, 1]]], [[3, [1, 2], [2, 1]]]]

如何将其扩展为完整列表?

[[1,2,3], [1,3,2], [2,1,3], [3,1,2], [2,3,1], [3,2,1]]

我认为这是某种递归,但我不知道如何。 提前谢谢

编辑:这是我为它写的一个函数,但它一直在说语法错误。

def expandList(aList):
    """expand a list"""

    finalList = []

    for j in aList:

        if type(j) != type(list):
            tempList = []
            tempList.append(j)

            finalList.append(tempList)

        else:
            finalList.extend(expandList(j))

    return finalList

编辑:糟糕,我的意思是:

[[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

不是:

[[1,2,3], [1,3,2], [2,1,3], [3,1,2], [2,3,1], [3,2,1]]

对于任何混淆感到抱歉。

2 个答案:

答案 0 :(得分:1)

你可能想试试这个,

l = [[[1, [2, 3], [3, 2]]], [[2, [1, 3], [3, 1]]], [[3, [1, 2], [2, 1]]]]
final_list = []
for k in l:
    for x in k:
        t = [x[0]]
        t.extend([i for i in x[1]])
        final_list.append(t)
        t = [x[0]]
        t.extend([i for i in x[2]])
        final_list.append(t)
print (final_list)

这会产生,

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

答案 1 :(得分:1)

假设您列出的确切输入结构,冗余list s:

big = [[[1, [2, 3], [3, 2]]], [[2, [1, 3], [3, 1]]], [[3, [1, 2], [2, 1]]]]
>>> [[a]+i for useless in big for a, *b in useless for i in b]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

假设没有冗余list s的清洁输入结构:

>>> big = [[1, [2, 3], [3, 2]], [2, [1, 3], [3, 1]], [3, [1, 2], [2, 1]]]
>>> [[a]+i for a, *b in big for i in b]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]