如标题所示,我正在尝试创建一个递归生成器,以查找给定列表的每个排列。这是我想出的功能,它不起作用:
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"""
i
作为列表的索引.extend
不返回任何内容,因此您遇到了NoneType
错误本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句