如何使用列表推导创建唯一身份列表

时间:2015-07-12 18:59:28

标签: python

我写了这段代码

def rec_offspring(n,offspring):

    if n == 1:
        return [[sprng] for sprng in offspring]
    else:
        return [[sprng1] for sprng1 in offspring] +\
        [sprng2 for sprng2 in rec_offspring(n-1,offspring)]

如何更改它以便返回uniqes列表?

例如:

rec_offspring(3,[1,2,3])

应该返回:

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

1 个答案:

答案 0 :(得分:0)

如果你想要一个递归函数,你可以使用回溯来创建排列:

def permute(a, i, out=None):
    if out is None:
        out = []
    if i == len(a):
        out.append(a)
    else:
        for j in range(i, len(a)):
            a[i], a[j] = a[j], a[i]
            permute(a, i + 1,out)
            a[i], a[j] = a[j], a[i]
    return out
print(permute([1,2,3],0))
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]