今天写代码有一块需要将四个数全排列,但是不知道如何把所有结果保存在一个列表中(用的是递归,照传统格式写的)
但是目前只能打印输出,不能保存
代码:
def per(pos,lt):
lst = lt
if pos == len(lst)-1:
print(lst)
else:
for index in range(pos,len(lst)):
lst[index],lst[pos] = lst[pos],lst[index]
per(pos+1,lst)
lst[index],lst[pos] = lst[pos],lst[index]
per(0,[1,2,3,4])
结果只能打印出来
[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 3, 2]
[1, 4, 2, 3]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 3, 1]
[2, 4, 1, 3]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 2, 3, 1]
[4, 2, 1, 3]
[4, 3, 2, 1]
[4, 3, 1, 2]
[4, 1, 3, 2]
[4, 1, 2, 3]
我曾尝试加上 listname.append(lst) 但无论放在哪都不对
我想要的结果
把结果返回到一个列表变量中