Python 3.x python中递归完成的数字列表的排列

Python 3.x python中递归完成的数字列表的排列,python-3.x,recursion,permutation,Python 3.x,Recursion,Permutation,所以基本上,我试图获取一个数字列表,并编写一个递归函数,输出列表中所有可能的输出 我的代码: def permutations(lst): if len(lst) <= 1: return lst l = [] for i in range(len(lst)): m = lst[i] remlst = lst[:i] + lst[i+1:] for p in permutations(remlst):

所以基本上,我试图获取一个数字列表,并编写一个递归函数,输出列表中所有可能的输出

我的代码:

def permutations(lst):
    if len(lst) <= 1:
        return lst
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
        return l

在itertools中有一个实现:

import itertools
for p in itertools.permutations(list):
   # do stuff

另外,要修复您自己的函数,请注意在“基本情况”中
len(lst),因为您迭代了
置换的结果

for p in permutations(remlst):
基本案例需要像递归案例一样返回列表列表,否则会出现错误
TypeError:只能将列表(而不是“int”)连接到列表

您还需要在外部for循环之后返回

def permutations(lst):
    if len(lst) <= 1:
        return [lst] # [[X]]
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
    return l # return at end of outer for loop
def置换(lst):

如果len(lst)给我们一个stacktrace:)
for p in permutations(remlst):
def permutations(lst):
    if len(lst) <= 1:
        return [lst] # [[X]]
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
    return l # return at end of outer for loop