排列的递归生成器

Recursive Generator for Permutations

如标题所示,我正在尝试创建一个递归生成器来查找给定列表的每个排列。这是我想出的函数,它不起作用:

def Permutations(l):
    if len(l) == 1:
        yield l
    else:
        for i in l:
            for j in Permutations(l[:i]+l[i+1:]):
                yield [i].extend(j)
            
l1 = [1,2,3]

for p in Permutations(l1):
    print(p)

我得到的错误是:

Traceback (most recent call last):
  File "idk.py", line 11, in <module>
    for p in Permutations(l1):
  File "idk.py", line 7, in Permutations
    yield [i].extend(j)
TypeError: 'NoneType' object is not iterable

您的代码存在一些问题

def Permutations(l):
    if len(l) == 1:
        yield l
    else:
        for idx, i in enumerate(l):
            for j in Permutations(l[:idx]+l[idx+1:]):
                yield [i] + j
                """ or
                lst = [i]
                lst.extend(j)
                yield lst"""
  1. 您使用值 i 作为列表的索引
  2. .extend 没有 return 任何东西,所以你收到 NoneType 错误